﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data.Entity;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using System.Net;
using System.Dynamic;
using ABDLight.Components;
using System.Diagnostics;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Security.Cryptography;
using System.Data.SQLite;

namespace ABDLight
{
    public partial class frmClean : Form
    {
        public DataTable tblFilter = new DataTable();

        public static void MyHandler(object sender, UnhandledExceptionEventArgs args)
        {

            Exception e = (Exception)args.ExceptionObject;
            //log.Error("Caught an unhandled exception! " + e.Message, e);
            System.IO.File.AppendAllText("loginfo.txt", System.DateTime.Now.ToLongTimeString() + "  Caught an unhandled exception! " + e.Message + "\r\n", Encoding.Unicode);
            Thread.CurrentThread.Abort(e.Message);
        }


        frmCleanAddress fCl = new frmCleanAddress();
        //public static readonly ILog log = LogManager.GetLogger(typeof(frmClean));
        public frmClean()
        {
            //log.Info("== Инициализация формы frmClean ==");
            InitializeComponent();


            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            this.data = data;

            this.Location = new System.Drawing.Point(0, 60);
            this.ClientSize = new System.Drawing.Size(SystemInformation.PrimaryMonitorSize.Width / 2, SystemInformation.PrimaryMonitorSize.Height / 4 * 3);

        }       
        public string data;
        public string[] __AddressesArr = { "" };

        private int FilterStatus = 0;

        public Dictionary<string, string> CleanResult /*= new Dictionary<string, string>()*/;

        private static CancellationTokenSource ts;// = new CancellationTokenSource();
        private CancellationToken ct;// = ts.Token;
        private string isTreadCleanStop;

        public static List<int> RecordCleanCount;

        public class LastCleanInfo
        {
            public string LastSelectedRow { get; set; }
            public string StartRow { get; set; }
            public string NumItem { get; set; }
            public string CleanType { get; set; }

            public LastCleanInfo()
            {
                LastSelectedRow = "";
                StartRow = "";
                NumItem = "";
                CleanType = "";
            }
            public static LastCleanInfo GetFileSettings(string FilePath = "")
            {
                if (string.IsNullOrEmpty(FilePath))
                {
                    FilePath = Application.StartupPath;
                }
                LastCleanInfo fs = new LastCleanInfo();
                aejw.cIni oIni = new aejw.cIni(FilePath + "\\settings.ini");
                fs.LastSelectedRow = oIni.ReadValue("LastCleanInfo", "LastSelectedRow", "0");
                fs.StartRow = oIni.ReadValue("LastCleanInfo", "StartRow", "0");
                fs.NumItem = oIni.ReadValue("LastCleanInfo", "NumItem", "0");
                fs.CleanType = oIni.ReadValue("LastCleanInfo", "CleanType", "AddressClean");

                return fs;

            }

            public static void SetFileSettings(LastCleanInfo fs = null, string FilePath = "", string FileName = "settings.ini")
            {
                if (fs == null)
                {
                    return;
                }

                if (string.IsNullOrEmpty(FilePath))
                {
                    FilePath = Application.StartupPath;
                }

                aejw.cIni oIni = new aejw.cIni(FilePath + "\\" + FileName);
                oIni.WriteValue("LastCleanInfo", "LastSelectedRow", fs.LastSelectedRow);
                oIni.WriteValue("LastCleanInfo", "StartRow", fs.StartRow);
                oIni.WriteValue("LastCleanInfo", "NumItem", fs.NumItem);
                oIni.WriteValue("LastCleanInfo", "CleanType", fs.CleanType);
            }
        }


        
        /// ////////////////////////
        ///  
        private DataColumn CloneColumn(DataColumn col)
        {
            DataColumn _col=new DataColumn();
            _col.ColumnName = col.ColumnName;
            _col.Caption = col.Caption;
            _col.DataType = col.DataType;
            return _col;
        }

        public void  LoadForm()
        {

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

            if ((((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true" && frmClean.cCfg.CheckType == "addrmatch") || (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true" && frmClean.cCfg.CheckType == "choose_addrmatch"))
            {

            }
            else
            {
                grdMain.LoadGrig(((frmMine)this.Owner).dtMain);
                fCl.grdVariant.LoadGrig(((frmMine)this.Owner).dtVariant);

            }


            if (tblFilter.Columns.Count == 0)
            {
                tblFilter.Columns.Add(new DataColumn("c_Columns", typeof(System.String)));
                tblFilter.Columns.Add(new DataColumn("c_oper", typeof(System.String)));
                tblFilter.Columns.Add(new DataColumn("c_value", typeof(System.String)));
                tblFilter.Columns.Add(new DataColumn("c_type", typeof(System.Int32)));
            }

            ((frmMine)this.Owner).cfg.Filter = "";


            grdMain.LoadGrig(((frmMine)this.Owner).dtMain);
            fCl.grdVariant.LoadGrig(((frmMine)this.Owner).dtVariant);
            cmbCountry.SelectedIndex = ((frmMine)this.Owner).cfg.defCountry;
            this.cmbCode.SelectedIndex = 0;


                aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\settings.ini");

                string isVisibleCollumn;
                int colInd = 0;
                DataColumn iqCheck = null;
                DataColumn isChanget = null;
                DataColumn isBad = null;


                foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                {
                    isVisibleCollumn = oIni.ReadValue("VisibleCollumns", col.Caption, "true");

                    if (isVisibleCollumn.ToLower() == "true")
                    {

                        if (grdMain.Grid.Columns[col.ColumnName] != null)
                        {
                            grdMain.Grid.Columns[col.ColumnName].Visible = true;
                        }

                        if (fCl.grdVariant.Grid.Columns[col.ColumnName] != null)
                        {
                            fCl.grdVariant.Grid.Columns[col.ColumnName].Visible = true;
                        }
                    }
                    else
                    {
                        if (grdMain.Grid.Columns[col.ColumnName] != null)
                        {
                            grdMain.Grid.Columns[col.ColumnName].Visible = true;
                        }
                        if (fCl.grdVariant.Grid.Columns[col.ColumnName] != null)
                        {
                            fCl.grdVariant.Grid.Columns[col.ColumnName].Visible = false;
                        }
                    }
                    colInd += 1;
                    oIni.WriteValue("VisibleCollumns", col.Caption, isVisibleCollumn);

                }

                cCfg.IsUseIndex = oIni.ReadValue("CleanOpt", "IsUseIndex", "false");

                if (cCfg.ErrorRowIndex != -1)
                {
                    this.btnStartCleaner.Text = "Продолжить чистку!";
                }


            fCl.Owner = this;
            fCl.Show();

            if (!ABDLight.Properties.Settings.Default.isLoadFromDB)
            {
                Hashtable pars = new Hashtable();
                pars.Add("Execute", "SavetoDB");
                frmProgress.frm = new frmProgress();
                frmProgress.frm.Owner = Program.applicationContext.MainForm;
                frmProgress.frm.ExecuteCommand("SavetoDB", pars);
            }

            //if (!ABDLight.Properties.Settings.Default.isLoadFromDB)
            //{
            //    // string TabName = ABDLight.Properties.Settings.Default.SQLiteTab;
            //    string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
            //    SQLiteData.DBCreate();
            //    SQLiteData.CreateTable(((frmMine)this.Owner).dtMain, TabName);
            //    SQLiteData.InsertTable(((frmMine)this.Owner).dtMain, TabName);

            //    //btnStartCleaner_Click(null, null);
            //}

            Refilter();
            grdMain.Grid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.None;

            fCl.label_all.Text = Convert.ToString(SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName, 0));
            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName, 3));
            
            if (!ABDLight.Properties.Settings.Default.isLoadFromDB)
                btnStartCleaner_Click(null, null);

            fCl.VariantEmptyHide();
            //GridEmptyHide();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
//MessageBox.Show(elapsedTime, "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        public void EmailCleanRow(DataRowView EmailString, int numRow)
        {
            if (numRow == -1) return; // проверка: какая колонка содержит входящие данные (если -1, то колонка не определилась!!!

            /////////// Обновление окна!
            Application.DoEvents();
            //this.Refresh();

            // получаем значение для проверки в сервисе (numRow - номер колонки во входящей строке грида)
            string StringOut = EmailString.Row[numRow].ToString();
            // меняем текст статус лэйбла
            //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется Email: " + StringOut + "\r\n" + " ЖДИТЕ ";
            // Переменная в которую будем получать ответ от сервиса.
            string responsetext = ""; 
            
            try
            {
                //вызываем сервис (получаем JSON строку)
                //responsetext = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.CheckEmail + StringOut).GetResponse().GetResponseStream()).ReadToEnd();

                string ServConn = ABDLight.Properties.Settings.Default.CheckEmail + StringOut.Trim() + "&login=" + ((frmMine)this.Owner).cfg.Login + "&pwd=" + ((frmMine)this.Owner).cfg.edPass;
                responsetext = new StreamReader(HttpWebRequest.Create(ServConn).GetResponse().GetResponseStream()).ReadToEnd();
                //responsetext = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.CheckEmail + StringOut + "&login=" + ((frmMine)this.Owner).cfg.Login + "&pwd=" + ((frmMine)this.Owner).cfg.edPass).GetResponse().GetResponseStream()).ReadToEnd();

                if (responsetext.EndsWith("]")) responsetext = "{\"CheckEmail\":" + responsetext + "}";
                else if (responsetext.EndsWith("}")) responsetext = "{\"CheckEmail\":[" + responsetext + "]}"; 
              
                //Производим Deserialize. В качестве типа данных указываем клас, соответствующий данному сервису.
                CheckedEmail StringIn = new JavaScriptSerializer().Deserialize<CheckedEmail>(responsetext);
                CheckEmailResponse CheckEmail = new JavaScriptSerializer().Deserialize<CheckEmailResponse>(responsetext);

                foreach (var item in CheckEmail.CheckEmail)
                {

                    if (cCfg.FuncType == "add")
                    {
                        //проверяем статус ответа сервиса (в зависимости от него изменяем грид [проставляем чекбоксы, вставляем ответы от сервиса, изменяем статус лэйблы])
                         if (item.c_valid== "0")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);

                        }
                         else if (item.c_valid == "3")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightPink;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);

                        }
                         else 
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightYellow;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);

                        }

                    }
                    if (cCfg.FuncType == "update")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);

                        if (item.c_valid == "0")
                        {
                            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Хороший");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                        }

                        else if (item.c_valid == "3")
                        {
                            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Плохой");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        }
                        else
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightYellow;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_message", item.c_status_desc);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_code", item.c_valid);

                        }

                    }
                }

            }
            catch (Exception e)
            {
                string er = e.ToString();
            }
        }


        /////////// АСТЕЛЛАС!
        public void CheckOrgDublCleanRow(DataRowView CheckString, int numRow)
        {
            if (numRow == -1) return;
            string StringOut = CheckString.Row[numRow].ToString();
            //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется FullName: " + StringOut + "\r\n" + " ЖДИТЕ ";
            string responsetext = "";
            int Num = 0;
            CheckOrgDubl StringIn = new CheckOrgDubl();

            try 
            {

                //запуск таймера
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                string Url = "";

                responsetext = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.CheckOrgDubl + StringOut).GetResponse().GetResponseStream()).ReadToEnd();

                //останока таймера и вывод результата
                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;

                // Format and display the TimeSpan value.
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    ts.Hours, ts.Minutes, ts.Seconds,
                    ts.Milliseconds / 10);
                Console.WriteLine(ABDLight.Properties.Settings.Default.CheckOrgDubl + StringOut + " || RunTime: " + elapsedTime);

                if(!String.IsNullOrEmpty(responsetext))
                {
                    responsetext = "{\"Orgs\":" + responsetext + "}";
                }
      
                StringIn = new JavaScriptSerializer().Deserialize<CheckOrgDubl>(responsetext);
            }
            catch 
            { }

            //Dictionary<string, string> res = JSONObject.ParseAllJSON();
            if (StringIn.Orgs != null)
            {
                foreach (var item in StringIn.Orgs)
                {
                    if (Num != 0) break;

                    string ss = "";
                    if (cCfg.FuncType == "add")
                    {


                        if (item.c_itog == "1" || item.c_itog == "5")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                        }
                        else if (item.c_itog == "3")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightPink;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                        }

                        else if (item.c_itog == "9")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightYellow;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                        }

                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);

                    }

                    if (cCfg.FuncType == "update")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);

                        if (item.c_itog == "1" || item.c_itog == "5")
                        {
                            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Хороший");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                        }
                        else if (item.c_itog == "3")
                        {
                            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Плохой");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        }
                        else if (item.c_itog == "9")
                        {
                            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Сомнительный");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        }

                    }

                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_phone", item.c_phone);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_address", item.c_address);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_post_code", item.c_post_code);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_itog", item.c_itog);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_fullname", item.c_fullname);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_kladr", item.c_kladr);

                    Num += 1;
                }
            }

        }


        public void PhoneCleanRow(DataRowView CheckString, int numRow)
        {
            if (numRow == -1) return;

            /////////// Обновление окна!
            //Application.DoEvents();
            //this.Refresh();
            ///////////

            string StringOut = CheckString.Row[numRow].ToString();
            //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется телефон: " + StringOut + "\r\n" + " ЖДИТЕ ";
            string responsetext = "";
            try
            {
                string pattern = @"[0-9]{13,15}";
                string input = StringOut;

                string _Kladr = "";
                string _Phone = StringOut.Trim();

                foreach (Match m in Regex.Matches(input, pattern))
                {
                    _Kladr = m.Value.Trim();
                    _Phone = StringOut.Replace(_Kladr, "").Trim();
                }

                responsetext = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.CheckPhone.Replace("phone_value", _Phone).Replace("KLADR_value", _Kladr)).GetResponse().GetResponseStream()).ReadToEnd();
                CheckedPhone StringIn = new JavaScriptSerializer().Deserialize<CheckedPhone>(responsetext.Replace("[{\"", "{\"").Replace("\"}]", "\"}"));

                if (cCfg.FuncType == "add")
                {
                   
                    
                    if (StringIn.valid == "0")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                        ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                    }
                    else if (StringIn.valid == "9")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightPink;
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                    }

                    else if (StringIn.valid == "4")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightYellow;
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                    }

                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);

                }

                if (cCfg.FuncType == "update")
                {
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);

                    if (StringIn.valid == "0")
                    {
                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Хороший");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                    }
                    else if (StringIn.valid == "9")
                    {
                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Плохой");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                    }
                    else if (StringIn.valid == "4")
                    {
                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Сомнительный");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                    }

                }

                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("kladr_out", StringIn.kladr_out);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("phone_formatted", StringIn.phone_formatted);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("phone_ded", StringIn.phone_ded);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("valid", StringIn.valid);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("status_desc", StringIn.status_desc);


            }
            catch
            {

            }
        }


        public void FIO1_CleanRow(DataRowView CheckString, int numRow)
        {
            if (numRow == -1) return;
           

            /////////// Обновление окна!
            //Application.DoEvents();
            //this.Refresh();
            ///////////

            string StringOut = CheckString.Row[numRow].ToString();
            //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется ФИО: " + StringOut + "\r\n" + " ЖДИТЕ ";
            string responsetext = "";

            try
            {
               
                    responsetext = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.CheckFIO + StringOut).GetResponse().GetResponseStream()).ReadToEnd();
                    CheckedFIO StringIn = new JavaScriptSerializer().Deserialize<CheckedFIO>(responsetext.Replace("[{\"", "{\"").Replace("\"}]", "\"}"));

                    if (cCfg.FuncType == "add")
                    {

                        if (StringIn.c_error == "13000000")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                        }
                        else if (StringIn.c_error == "13000001")
                        {
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightPink;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                        }
                        else if (StringIn.c_error != "13000000")
                        {

                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                            ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightYellow;
                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");

                        }

                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);

                }

                if (cCfg.FuncType.ToLower() == "update")
                {
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);

                    if (StringIn.c_error == "13000000")
                    {

                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Хороший");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                    }
                    else if (StringIn.c_error == "13000001")
                    {
                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Плохой");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                    }
                    else if (StringIn.c_error != "13000000")
                    {
                        changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString(), "Сомнительный");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                    }

                   
                }

                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_error", StringIn.c_error);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_error_status", StringIn.c_error_status);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_fname", StringIn.c_fname);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_lname", StringIn.c_lname);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_mname", StringIn.c_mname);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("c_gender", StringIn.c_gender);
                //

            }
        
            
            catch
            {
                var stop = 1;
            }
        }

        
        public void CleanRow(DataRowView AddrString, int numRow,bool SaveResult = true,bool UseService = true)
        {
            if (!fCl.Created) {
                fCl = new frmCleanAddress();
                fCl.grdVariant.LoadGrig(((frmMine)this.Owner).dtVariant);
                fCl.VariantEmptyHide();
                fCl.Owner = this; 
                fCl.Show(); }    
            if (fCl.WindowState == FormWindowState.Minimized) fCl.WindowState = FormWindowState.Normal;

            string isOld = ((frmMine)this.Owner).cfg.isJSON;
            string NowChoose = "";
            string NowChooseValue = "";


            if (numRow == -1) return;

            //вывод на форму проверяемой строки
            string AddrStringStr = AddrString.Row[numRow].ToString();
            if (AddrStringStr == "") AddrStringStr = AddrString.Row[cCfg.StartInd].ToString();
            //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется адрес: " + AddrStringStr + "\r\n" + " ЖДИТЕ "; 
            //

            string  AddressOtvet = "";
            string AddressOtvetErrorMsg = "";

            //подключение ini файла
            aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\ServiceErrors.ini");
            
            
            if(frmClean.cCfg.CheckType == "choose_addrmatch")
            { 
                aejw.cIni oIniSet = new aejw.cIni(Application.StartupPath + "\\settings.ini");
                //
         

                string __Addresses = "";
            
            
                int addrmatch_num = 0;
                string addrmatch_numStr = oIniSet.ReadValue("choose_addrmatch", "addrmatch_num");
            
                int num_Now = 0;
                int.TryParse(addrmatch_numStr, out addrmatch_num);

                while (addrmatch_num - num_Now > 0)
                {
                    num_Now++;

                    __Addresses += oIniSet.ReadValue("choose_addrmatch", num_Now.ToString());
                    __Addresses += "&&";
  
                }


                __Addresses += "__end";
                __Addresses = __Addresses.Replace("&&__end", "");
                __AddressesArr = __Addresses.Split(new string[] { "&&" }, StringSplitOptions.None);

                frmChooseAddr _frmChooseAddr = new frmChooseAddr();
                _frmChooseAddr.Text = "Выберите вариант адреса!";

                _frmChooseAddr.textBox1.Text = ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow][__AddressesArr[0]].ToString();
 
                _frmChooseAddr.label1.Text = __AddressesArr[0];
                _frmChooseAddr.radioButton1.Text = __AddressesArr[0];
            
                _frmChooseAddr.textBox2.Text = ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow][__AddressesArr[1]].ToString();
                _frmChooseAddr.label2.Text = __AddressesArr[1];
                _frmChooseAddr.radioButton2.Text = __AddressesArr[1];
            
                _frmChooseAddr.textBox3.Text = ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow][__AddressesArr[2]].ToString();
                _frmChooseAddr.label3.Text = __AddressesArr[2];
                _frmChooseAddr.radioButton3.Text = __AddressesArr[2];

                _frmChooseAddr.textBox4.Text = ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow][__AddressesArr[0]].ToString();
                _frmChooseAddr.label4.Text = "Другой адрес";
                _frmChooseAddr.radioButton4.Text = __AddressesArr[0];

                Color tmpColore = ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor ;

                int tmp = _frmChooseAddr.textBox1.Text.Length;
                oIniSet.WriteValue("choose_addrmatch", "NowChoose", 1.ToString());

                ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor = Color.Lime;
                //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется адрес: " + textBox1.Text + "\r\n" + " ЖДИТЕ "; 
            
                _frmChooseAddr.radioButton1.Checked = true;

                if (_frmChooseAddr.textBox2.Text.Length > tmp)
                {
                    tmp = _frmChooseAddr.textBox2.Text.Length;
                    _frmChooseAddr.radioButton2.Checked = true;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[1]].Style.BackColor = Color.Lime;
                    //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется адрес: " + textBox2.Text + "\r\n" + " ЖДИТЕ "; 
                    oIniSet.WriteValue("choose_addrmatch", "NowChoose", 2.ToString());
                }
                if (_frmChooseAddr.textBox3.Text.Length > tmp)
                {
                    tmp = _frmChooseAddr.textBox3.Text.Length;
                    _frmChooseAddr.radioButton3.Checked = true;
                    oIniSet.WriteValue("choose_addrmatch", "NowChoose", 3.ToString());
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[1]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[2]].Style.BackColor = Color.Lime;
                    //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется адрес: " + textBox3.Text + "\r\n" + " ЖДИТЕ "; 
                }



                _frmChooseAddr.ShowDialog();
                int tmpChoose = 0;
            
                NowChoose = oIniSet.ReadValue("choose_addrmatch", "NowChoose");
                NowChooseValue = oIniSet.ReadValue("choose_addrmatch", "NowChooseValue");
                int.TryParse(NowChoose, out tmpChoose);

            
                if (tmpChoose != 4 && tmpChoose != -1) 
                {
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[1]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[2]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[tmpChoose - 1]].Style.BackColor = Color.Lime;
                }else
                {
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[0]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[1]].Style.BackColor = tmpColore;
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).Cells[__AddressesArr[2]].Style.BackColor = tmpColore;
                }
         


                ((frmMine)this.Owner).dtMain.Rows[numRow].SetField("iqWorkAddress", NowChooseValue);



                //StatysLabel.Text = "Обрабатывается " + (cCfg.StartRow + 1).ToString() + " строка." + "Проверяется адрес: " + NowChooseValue + "\r\n" + " ЖДИТЕ ";
            }
            Application.DoEvents();
            //проверка на корректность входящих данных (строка для проверки больше 5 символов)
            if (string.IsNullOrEmpty(AddrStringStr) || AddrStringStr.Length < 5  && cCfg.FuncType == "add")
            {
                string errDateTime = "";
                errDateTime += System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + "_" +
                System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();


                oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrFileName", cCfg.LastFilePath + "\\" + cCfg.LastFileName);
                oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrRowIndex", cCfg.StartRow.ToString());
                oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrInAddr", AddrStringStr);
                oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrAddressOtvet", AddressOtvet);
                oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrAddressOtvet", AddressOtvet.ToString());

                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqFullAddress", AddressOtvet.ToString());
                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStatus", "Сервис не отвечает");
                ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.DarkRed;
                AddressOtvet = null;

                fCl.textBox21.Text = "";
                fCl.textBox2.Text = "";
                fCl.textBox4.Text = "";
                fCl.textBox5.Text = "";
                fCl.textBox7.Text = "";
                fCl.textBox9.Text = "";
                fCl.textBox6.Text = "";
                fCl.textBox8.Text = "";
                fCl.textBox10.Text = "";
                fCl.textBox11.Text = "";
                fCl.textBox12.Text = "";
                fCl.textBox13.Text = "";
                fCl.textBox16.Text = "";
                fCl.textBox17.Text = "";
                fCl.textBox18.Text = "";
                fCl.textBox19.Text = "";
                fCl.textBox14.Text = "";
                fCl.textBox15.Text = "";
                fCl.textBox23.Text = "";

         
                //StatysLabel.Text = "Обрабатываемая строка выдала ошибку! "  + "\r\n" + " ЖДИТЕ ";
                cCfg.ErrorRowIndex = cCfg.StartRow;
                return;
            }
            //
            if (UseService)
            {
                try
                {
                    AddressOtvet = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.SearchAddr_Url + AddrStringStr + "&login=" + ((frmMine)this.Owner).cfg.Login + "&pwd=" + ((frmMine)this.Owner).cfg.edPass).GetResponse().GetResponseStream()).ReadToEnd();                   
                }
                catch
                { 
                    AddressOtvet = null; 
                }
            }
            else
            {
                AddressOtvet = SQLiteData.GetJsonCleanResultByID(ABDLight.Properties.Settings.Default.CleanFileName, Convert.ToInt32(AddrString.Row["ID_IQ"]));
            }
                //

            if (!string.IsNullOrEmpty(AddressOtvet))
            {

                try
                {


                    if (UseService)
                    {
                        if (AddressOtvet.EndsWith("]"))
                        {
                            AddressOtvet = "{\"Address\":" + AddressOtvet + "}";
                        }
                        else if (AddressOtvet.EndsWith("}"))
                        {
                            AddressOtvet = "{\"Address\":[" + AddressOtvet + "]}";
                        }
                    }


                    templateResponse Address = new JavaScriptSerializer().Deserialize<templateResponse>(AddressOtvet);
                    int NumItem = 0;

                    //Проверка на бабло
                    if (Address.Address[0].msg == "Уважаемый абонент у Вас закончился суточный лимит бесплатного использования сервиса!"
                         ||Address.Address[0].msg == "Уважаемый абонент у Вас на счету закончились средства! Просим пополнить баланс Вашего лицевого счета")
                    {
                        var result = MessageBox.Show(Address.Address[0].msg + "\nПосетите сайт http://iqdq.ru для пополнения Вашего счёта!", "Внимание",MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                        //if (result == DialogResult.OK)
                        //{
                        //    cCfg.isWork = true;
                        //    cCfg.ErrorRowIndex = -1;
                        //    CleanRow(AddrString, numRow);
                        //}
                        //else
                        //{
                        //    cCfg.isWork = false;
                        //    cCfg.isPause = true;
                        //    cCfg.FuncType = "select";
                        //    cCfg.ErrorRowIndex = cCfg.StartRow;
                        //    //cCfg.StartRow = 0;
                        //    btnCancel.Visible = false;
                        //    StatysLabel.Visible = false;
                        //    // cCfg.ErrorRowIndex = - 1;
                        //     //this.Close();
                        //     //return;
                        //}
                    }
                    


                    if ((AddrStringStr == null || AddrStringStr.Length < 5 || Address.Address.Count() == 0) && cCfg.FuncType == "add")
                    {
                        // все плохо
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                        ((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.LightPink;


                        ////////////////////////////////////////////////////////// 
                    }

                    if (cCfg.FuncType == "add")
                    {
                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);
                    }

                    foreach (var item in Address.Address)
                    {
                        
                        //Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}", item.full_name, item.street, item.house, item.flat, item.status, item.ErrorCode, item.GetHashCode());
                        if (NumItem == cCfg.NumItem)
                        {
                            //tabPage1
                            fCl.textBox1.Text = AddrString.Row[numRow].ToString();
                            //fCl.textBox1.Text = "";
                            fCl.textBox22.Text = AddrString.Row[cCfg.StartInd].ToString();
                            fCl.cid.Text = AddrString.Row["ID_IQ"].ToString();
                            string val = AddrStringStr;


                                string pattern = @"\d{6,6}";
                                string input = AddrStringStr;

                                foreach (Match m in Regex.Matches(input, pattern))
                                {

                                    if (!string.IsNullOrEmpty(m.Value) && (frmMine)this.Owner != null)
                                    {
                                        ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqPostCodeIn", m.Value);

                                    }
                                }

                            //Присваеваем старым полям значения полей из нового сервиса.
                            if (isOld.ToLower() == "false")
                            {
                                if (!String.IsNullOrEmpty(item.c_zipcode)) item.post_code = item.c_zipcode;
                                if (!String.IsNullOrEmpty(item.c_address_full)) item.full_name = item.c_address_full;
                                if (!String.IsNullOrEmpty(item.c_region_name)) item.region = item.c_region_name;
                                if (!String.IsNullOrEmpty(item.c_region_abbr)) item.region_type = item.c_region_abbr;
                                if (!String.IsNullOrEmpty(item.c_city_name)) item.city = item.c_city_name;
                                if (!String.IsNullOrEmpty(item.c_city_abbr)) item.city_type = item.c_city_abbr;
                                if (!String.IsNullOrEmpty(item.c_community_name)) item.np = item.c_community_name;
                                if (!String.IsNullOrEmpty(item.c_community_abbr)) item.np_type = item.c_community_abbr;

                                if (!String.IsNullOrEmpty(item.c_street_name)) item.street = item.c_street_name;
                                if (!String.IsNullOrEmpty(item.c_street_abbr)) item.street_type = item.c_street_abbr;
                                if (!String.IsNullOrEmpty(item.c_district_name)) item.subregion = item.c_district_name;
                                if (!String.IsNullOrEmpty(item.c_district_abbr)) item.c_SubRegionType = item.c_district_abbr;

                                if (!String.IsNullOrEmpty(item.c_index_out)) item.post_code = item.c_index_out;
                                if (!String.IsNullOrEmpty(item.c_kladr)) item.KLADR = item.c_kladr;
                                if (!String.IsNullOrEmpty(item.c_status_error)) item.ErrorCode = item.c_status_error;
                                if (!String.IsNullOrEmpty(item.c_house_error_desc)) item.status = item.c_house_error_desc;
                                if (!String.IsNullOrEmpty(item.c_addr_out)) item.full_name = item.c_addr_out;

                                if (!String.IsNullOrEmpty(item.c_addr_lost)) item.lost = item.c_addr_lost;

                                if (!String.IsNullOrEmpty(item.msg)) { item.status = item.msg; AddressOtvetErrorMsg = item.msg; }



                                if (item.c_json_kvant != null && !String.IsNullOrEmpty(item.c_json_kvant.ToString()))
                                {
                                    foreach (KeyValuePair<string, object> kvant in item.c_json_kvant as Dictionary<string, object>)
                                    {

                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "house") item.house = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "case") item.Case = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "build") item.build = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "liter") item.liter = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vlad") item.vlad = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "land") item.vlad = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "uch") item.uch = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "block") item.block = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "pav") item.pav = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "pom") item.pom = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "office") item.office = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "flat") item.flat = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "kom") item.kom = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vch") item.vch = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "abon") item.abon = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "kab") item.kab = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vch") item.vch = kvant.Value.ToString();
                                    }
                                }     

                            }


                            fCl.textBox21.Text = item.post_code;
                            fCl.textBox2.Text = item.full_name;
                            fCl.textBox4.Text = item.house;
                            fCl.textBox5.Text = item.Case;
                            fCl.textBox7.Text = item.build;
                            fCl.textBox9.Text = item.liter;
                            fCl.textBox6.Text = item.vlad;
                            fCl.textBox8.Text = item.uch;
                            fCl.textBox10.Text = item.block;
                            fCl.textBox11.Text = item.pav;
                            fCl.textBox12.Text = item.office;
                            fCl.textBox13.Text = item.flat;
                            fCl.textBox16.Text = item.kom;
                            fCl.textBox17.Text = item.vch;
                            fCl.textBox18.Text = item.abon;
                            fCl.textBox19.Text = item.kab;
                            fCl.textBox14.Text = item.lost;
                            fCl.textBox20.Text = item.status.Replace(";", ",");
                            fCl.textBox15.Text = "";
                            fCl.textBox23.Text = "";
                            //
                            if(SaveResult)
                            {
                                int isGood = item.ErrorCode.IndexOf("|0000");

                                if (isOld.ToLower() == "false")
                                {
                                    isGood = item.ErrorCode.IndexOf("0000"); ;
                                }


                                if ((frmMine)this.Owner != null)
                                    if ((isGood < 0) || (item.ErrorCode.ToString() == "") || (string.IsNullOrEmpty(item.post_code)) || (!UseIndexCheck(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["iqPostCodeIn"].ToString().ToLower(), item.post_code.ToString().ToLower())))
                                    {
                                        if (cCfg.FuncType == "add" || cCfg.FuncType == "update")
                                        {
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Сомнительный");

                                        }
                                        if (cCfg.FuncType == "update")
                                        {
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);
                                        }
                                    }
                                    else if (UseIndexCheck(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["iqPostCodeIn"].ToString().ToLower(), item.post_code.ToString().ToLower()))
                                    {

                                        if (cCfg.FuncType == "add" || cCfg.FuncType == "update")
                                        {
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", true);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", false);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", false);
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Хороший");

                                        }

                                        if (cCfg.FuncType == "update")
                                        {
                                            ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isChanget", true);
                                        }
                                    }

                                string AddressString = item.full_name;
                                if (item.house != "") AddressString += ", дом " + item.house;
                                if (item.Case != "") AddressString += ", кор. " + item.Case;
                                if (item.build != "") AddressString += ", стр. " + item.build;
                                if (item.liter != "") AddressString += ", лит. " + item.liter;
                                if (item.vlad != "") AddressString += ", влад. " + item.vlad;
                                if (item.uch != "") AddressString += ", уч. " + item.uch;
                                if (item.block != "") AddressString += ", блок " + item.block;
                                if (item.pav != "") AddressString += ", пав. " + item.pav;
                                if (item.office != "") AddressString += ", офис " + item.office;
                                if (item.flat != "") AddressString += ", кв. " + item.flat;
                                if (item.kom != "") AddressString += ", ком. " + item.kom;
                                if (item.vch != "") AddressString += ", вч " + item.vch;
                                if (item.abon != "") AddressString += ", а/я " + item.abon;
                                if (item.kab != "") AddressString += ", каб " + item.kab;

                            
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqPostCode", item.post_code);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqFullAddress", item.full_name);                          
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqHouse", item.house);
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqCase", item.Case);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqBuild", item.build);                         
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqLiter", item.liter);                    
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqVlad", item.vlad);                         
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqBlock", item.block);
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqPom", item.pom);
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqPav", item.pav);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqUch", item.uch);                        
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqObsch", item.obsch);                         
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqFlat", item.flat);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqKom", item.kom);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqOffice", item.office);                            
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqKab", item.kab);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqAbon", item.abon);                      
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqVch", item.vch);                       
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqKLADR", item.KLADR);                         
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqError", item.ErrorCode);                       
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStatus", item.status.Replace(";", ","));                         
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqCountry", cmbCountry.Items[((frmMine)this.Owner).cfg.defCountry].ToString());                          
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqRegion", item.region);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqRegionType", item.region_type);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqSubRegion", item.subregion);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqSubRegionType", "");                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqCity", item.city);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqCityType", item.city_type);                          
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqNp", item.np);                           
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqNpType", item.np_type);                            
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStreet", item.street);
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStreetType", item.street_type);
                                ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqLostAddr", item.lost);

                                if (((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["textStatus"].ToString() == "Хороший")
                                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqWorkAddress", AddressString);                                                      
                            }
                            if (cCfg.FuncType != "add")
                            {
                                if ((frmMine)this.Owner != null)
                                {
                                    ((frmMine)this.Owner).dtVariant.Rows.Add( /*Address.GUID,*/ item.post_code, item.full_name, item.house, item.Case, item.build, item.liter, item.vlad, item.block, item.pom, item.pav, item.uch, item.obsch, item.flat, item.kom, item.office, item.kab, item.abon, item.vch,"", item.KLADR, item.lost, item.ErrorCode, item.status, cmbCountry.Items[((frmMine)this.Owner).cfg.defCountry].ToString(), item.region, item.region_type, item.subregion, "", item.city, item.city_type, item.np, item.np_type, item.street, item.street_type);
                                }
                            }

                            NumItem += 1;
                        }
                        else
                        {
                            //Присваеваем старым полям значения полей из нового сервиса.
                            if (isOld.ToLower() == "false")
                            {
                                if (!String.IsNullOrEmpty(item.c_zipcode)) item.post_code = item.c_zipcode;
                                if (!String.IsNullOrEmpty(item.c_address_full)) item.full_name = item.c_address_full;
                                if (!String.IsNullOrEmpty(item.c_region_name)) item.region = item.c_region_name;
                                if (!String.IsNullOrEmpty(item.c_region_abbr)) item.region_type = item.c_region_abbr;
                                if (!String.IsNullOrEmpty(item.c_city_name)) item.city = item.c_city_name;
                                if (!String.IsNullOrEmpty(item.c_city_abbr)) item.city_type = item.c_city_abbr;
                                if (!String.IsNullOrEmpty(item.c_community_name)) item.np = item.c_community_name;
                                if (!String.IsNullOrEmpty(item.c_community_abbr)) item.np_type = item.c_community_abbr;

                                if (!String.IsNullOrEmpty(item.c_street_name)) item.street = item.c_street_name;
                                if (!String.IsNullOrEmpty(item.c_street_abbr)) item.street_type = item.c_street_abbr;
                                if (!String.IsNullOrEmpty(item.c_district_name)) item.subregion = item.c_district_name;
                                if (!String.IsNullOrEmpty(item.c_district_abbr)) item.c_SubRegionType = item.c_district_abbr;

                                if (!String.IsNullOrEmpty(item.c_index_out)) item.post_code = item.c_index_out;
                                if (!String.IsNullOrEmpty(item.c_kladr)) item.KLADR = item.c_kladr;
                                if (!String.IsNullOrEmpty(item.c_status_error)) item.ErrorCode = item.c_status_error;
                                if (!String.IsNullOrEmpty(item.c_house_error_desc)) item.status = item.c_house_error_desc;
                                if (!String.IsNullOrEmpty(item.c_addr_out)) item.full_name = item.c_addr_out;

                                if (!String.IsNullOrEmpty(item.c_addr_lost)) item.lost = item.c_addr_lost;

                                if (item.c_json_kvant != null && !String.IsNullOrEmpty(item.c_json_kvant.ToString()))
                                {
                                    foreach (KeyValuePair<string, object> kvant in item.c_json_kvant as Dictionary<string, object>)
                                    {

                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "house") item.house = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "case") item.Case = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "build") item.build = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "liter") item.liter = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vlad") item.vlad = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "land") item.vlad = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "uch") item.uch = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "block") item.block = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "pav") item.pav = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "pom") item.pom = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "office") item.office = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "flat") item.flat = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "kom") item.kom = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vch") item.vch = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "abon") item.abon = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "kab") item.kab = kvant.Value.ToString();
                                        if (!String.IsNullOrEmpty(kvant.Key) && kvant.Key.ToLower() == "vch") item.vch = kvant.Value.ToString();
                                    }
                                }
                            }
                            //
                            if (cCfg.FuncType != "add")
                            {
                                //((frmMine)this.Owner).dtVariant.Rows.Add(false, Address.GUID, item.post_code, item.full_name, item.house, item.Case, item.build, item.liter, item.vlad, item.block, item.pom, item.pav, item.uch, item.obsch, item.flat, item.kom, item.office, item.kab, item.abon, item.vch, item.KLADR, item.ErrorCode, item.status, cmbCountry.Items[((frmMine)this.Owner).cfg.defCountry].ToString(), item.region, item.region_type, item.subregion, "", item.city, item.city_type, item.np, item.np_type, item.street, item.street_type);
                                ((frmMine)this.Owner).dtVariant.Rows.Add(/*Address.GUID,*/ item.post_code, item.full_name, item.house, item.Case, item.build, item.liter, item.vlad, item.block, item.pom, item.pav, item.uch, item.obsch, item.flat, item.kom, item.office, item.kab, item.abon, item.vch, "", item.KLADR, item.lost, item.ErrorCode, item.status, cmbCountry.Items[((frmMine)this.Owner).cfg.defCountry].ToString(), item.region, item.region_type, item.subregion, "", item.city, item.city_type, item.np, item.np_type, item.street, item.street_type);
                            }
                            
                            NumItem += 1;
                        }
                    }

                    if (cCfg.FuncType == "update" || cCfg.FuncType == "add")
                    {
                       
                    }

                }
                catch(Exception e)
                {
                    string errDateTime = "";
                    errDateTime += System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + "_" +
                    System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();

                    oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrFileName", cCfg.LastFilePath + "\\" + cCfg.LastFileName);
                    oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrRowIndex", cCfg.StartRow.ToString());
                    oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrInAddr", AddrStringStr);
                    oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrAddressOtvet", AddressOtvet);
                    oIni.WriteValue("ServiceErrors" + "_" + errDateTime, "ErrAddressOtvet", AddressOtvet.ToString());

                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isCheck", false);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("isBad", true);
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("textStatus", "Плохой");
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqFullAddress", "");
                    //((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStatus", "Поиск не дал результатов!");
                    ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow].SetField("iqStatus", AddressOtvetErrorMsg);
                    //((DataGridViewRow)grdMain.Grid.Rows[cCfg.StartRow]).DefaultCellStyle.BackColor = Color.DarkRed;
                    AddressOtvet = null;

                    
                    fCl.textBox21.Text = "";
                    fCl.textBox2.Text = "";
                    fCl.textBox4.Text = "";
                    fCl.textBox5.Text = "";
                    fCl.textBox7.Text = "";
                    fCl.textBox9.Text = "";
                    fCl.textBox6.Text = "";
                    fCl.textBox8.Text = "";
                    fCl.textBox10.Text = "";
                    fCl.textBox11.Text = "";
                    fCl.textBox12.Text = "";
                    fCl.textBox13.Text = "";
                    fCl.textBox16.Text = "";
                    fCl.textBox17.Text = "";
                    fCl.textBox18.Text = "";
                    fCl.textBox19.Text = "";
                    fCl.textBox14.Text = "";
                    fCl.textBox15.Text = "";
                    fCl.textBox23.Text = "";
                    fCl.textBox20.Text = ((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow]["iqStatus"].ToString(); 

                    cCfg.ErrorRowIndex = cCfg.StartRow;

                

                }
            }
            else
            {
                if (isOld.ToLower() == "true")
                {
                    //Старый способ
                    try
                    {
                        IQCleanServices.IQAddressService srv = new IQCleanServices.IQAddressService();
                        srv.Url = ABDLight.Properties.Settings.Default.AddressCleanASMX;
                        AddressOtvet = srv.CheckAddress(ABDLight.Properties.Settings.Default.Login, ABDLight.Properties.Settings.Default.Pwd, AddrString.Row[0].ToString(), "г. Москва, ул. Кравченко, д. 12, по. 1").Replace("case", "Case");

                        var stop = 1;
                    }
                    catch
                    {
                        var result = MessageBox.Show("Проверте Ваше соединение с Интернет! Вы желаете прервать чистку? ", "Внимание",
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Question);
                        if (result == DialogResult.No)
                        {
                            cCfg.isWork = true;
                        }
                        else
                        {
                            cCfg.isWork = false;
                            cCfg.FuncType = "select";
                            ((frmMine)this.Owner).dtVariant.Rows.Clear();
                            ((frmMine)this.Owner).dtMain.Rows.Clear();
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            this.Close();
                            //return;
                        }
                    }
                }
                else if (isOld.ToLower() == "false")
                {
                    //Новый способ

                    try
                    {
                        AddressOtvet = new StreamReader(HttpWebRequest.Create(ABDLight.Properties.Settings.Default.SearchAddr_Url + "г. Москва, ул. Кравченко, д. 12, по. 1").GetResponse().GetResponseStream()).ReadToEnd();
                    }
                    catch
                    {
                        var result = MessageBox.Show("Проверте Ваше соединение с Интернет! Вы желаете прервать чистку? ", "Внимание",
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Question);
                        if (result == DialogResult.No)
                        {
                            cCfg.isWork = true;
                        }
                        else
                        {
                            cCfg.isWork = false;
                            cCfg.FuncType = "select";
                            ((frmMine)this.Owner).dtVariant.Rows.Clear();
                            ((frmMine)this.Owner).dtMain.Rows.Clear();
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            this.Close();
                            //return;
                        }
                    }
                }             
            }



            string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
            //SQLiteData.UpdateRow(((frmMine)this.Owner).dtMain, TabName, numRow);
            SQLiteData.UpdateRow(AddrString, TabName);

            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 3));

            fCl.textBox22.Focus();
            fCl.VariantEmptyHide();
            //GridEmptyHide();
           
        }

        private void btnStartCleaner_Click(object sender, EventArgs e)
        {
            string TabName = ABDLight.Properties.Settings.Default.CleanFileName;

            fCl.label_all.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 0));
            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 3));      

            if (ABDLight.Properties.Settings.Default.Login == "" || ABDLight.Properties.Settings.Default.edPwd == "")
            {
      
                MessageBox.Show("Вы не верно указали логин или пароль! Повторите ввод!", "Внимание",
                                                      MessageBoxButtons.OK,
                                                      MessageBoxIcon.Error);

                        this.Close();
                        return;
            }


            //Понеслась многопотчная чистка
            Hashtable pars = new Hashtable();
            pars.Add("Execute", "TreadClean");
            frmProgress.frm = new frmProgress();
            frmProgress.frm.Owner = this;
            frmProgress.frm.ExecuteCommand("Clean", pars);
            pars.Clear();

            pars.Add("Execute", "CheckCleanFile");
            frmProgress.frm = new frmProgress();
            frmProgress.frm.Owner = this;
            frmProgress.frm.ExecuteCommand("CheckFile", pars);

            LoadFileFromDB(ABDLight.Properties.Settings.Default.CleanFileName);
            grdMain.LoadGrig(((frmMine)this.Owner).dtMain);
            fCl.grdVariant.LoadGrig(((frmMine)this.Owner).dtVariant);
            fCl.VariantEmptyHide();
            grdMain.Refresh();
            //GridEmptyHide();

            fCl.label_all.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 0));
            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 3));

            if (isTreadCleanStop != null) 
                MessageBox.Show(isTreadCleanStop + "\nПосетите сайт http://iqdq.ru для пополнения Вашего счёта!\n", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
                if (SQLiteData.GetRecordCount(TabName,4) > 0)
                    MessageBox.Show("В результате чистки не было обработано записей:" + SQLiteData.GetRecordCount(TabName, 4).ToString() + "!\nВозможные причины:\n\t - ручная остановка чистки\n\t - проблемы с соединением с сетью\n\t - загруженность сервера\n\t - другие причины\nДля того, чтобы прочистить необработанные данные, нажмите кнопку 'Прочистить'(программа прочистит только необработанные данные)"                   
                        , "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  
        }















        public void autoStartCleaner()
        {
            //this.ParentForm.Close();
            if (ABDLight.Properties.Settings.Default.Login == "" || ABDLight.Properties.Settings.Default.edPwd == "")
            {

                MessageBox.Show("Вы не верно указали логин или пароль! Повторите ввод!", "Внимание",
                                                      MessageBoxButtons.OK,
                                                      MessageBoxIcon.Error);

                this.Close();
                return;
            }

            this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Count.ToString();
            /////////////////////////////////////////////

            int cCfgIndNum = 0;
            cCfg.Ind = -1;

            foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
            {
                if ("iqWorkAddress" == col.ColumnName)
                {
                    cCfg.Ind = cCfgIndNum;
                }
                cCfgIndNum += 1;
            }

            if (cCfg.Ind == -1)
            {
                MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                  MessageBoxButtons.OK,
                                                  MessageBoxIcon.Warning);
                return;
            }

            IPStatus status = new IPStatus();
            try
            {
                Ping p = new Ping();
                PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                status = pr.Status;
            }
            catch { }
            if (status == IPStatus.Success)
            {
                //StatysLabel.Text = "Соединение с сервером установлено! Начинаю чистку.";
            }
            else
            {
                MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                //StatysLabel.Text = "Соединение с сервером не установлено! Начинаю чистку.";
            }

            btnCancel.Visible = true;
            StatysLabel.Visible = true;
            cCfg.isWork = true;
            cCfg.FuncType = "add";

            for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
            {
                toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                cCfg.StartRow += 1;
                lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                if (!cCfg.isWork)
                {
                    cCfg.FuncType = "select";
                    cCfg.StartRow = 0;
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;
                    //this.Close();
                    //return;
                }
                
                // ((frmMine)this.Owner).dtVariant.Rows.Clear();           
            }
            ((frmMine)this.Owner).dtVariant.Rows.Clear();
            cCfg.StartRow = 0;
            cCfg.FuncType = "select";
            btnCancel.Visible = false;
            StatysLabel.Visible = false;

            //StatysLabel.Text = "Адреса разобраны!";
            MessageBox.Show("Адреса разобраны!", "Внимание",
                                                      MessageBoxButtons.OK,
                                                      MessageBoxIcon.Information);
            //StatysLabel.Text = "";

        }

        public void OneRowClean(int StartRow, bool SaveResult = true, bool UseService = true)
        {
            if (ABDLight.Properties.Settings.Default.Login == "" || ABDLight.Properties.Settings.Default.edPwd == "")
            {

                MessageBox.Show("Вы не верно указали логин или пароль! Повторите ввод!", "Внимание",
                                                  MessageBoxButtons.OK,
                                                  MessageBoxIcon.Error);
                    this.Close();
                    return;
            }


            cCfg.StartRow = StartRow;
             
            if (cCfg.StartRow < 0)
            {
                return;
            }

             ((frmMine)this.Owner).dtVariant.Rows.Clear();
             
             int cCfgIndNum = 0;
             cCfg.Ind = -1;

             if (frmClean.cCfg.CheckType == "emailmatch")
             {
                 foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                 {
                     if ("iqWorkEmail" == col.ColumnName)
                     {
                         cCfg.Ind = cCfgIndNum;
                     }
                     cCfgIndNum += 1;
                 }

                 if (cCfg.Ind == -1)
                 {
                     MessageBox.Show("iqWorkEmail (Исходный Email) не найден!!!!", "Внимание",
                                                       MessageBoxButtons.OK,
                                                       MessageBoxIcon.Warning);
                     return;
                 }


                 IPStatus status = new IPStatus();
                 try
                 {
                     Ping p = new Ping();
                     PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                     status = pr.Status;
                 }
                 catch { }
                 if (status == IPStatus.Success)
                 {

                 }
                 else
                 {
                     MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                     //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                 }

              
                 if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                 {
                     //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";                   
                     EmailCleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                 }
                 //StatysLabel.Text = "";
                 cCfg.StartRow = 0;
                 cCfg.FuncType = "select";

             }
             else if (frmClean.cCfg.CheckType == "phonematch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkPhone" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkPhone (Исходные данные) не найдены!!!!", "Внимание",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Warning);
                        return;
                    }


                    IPStatus status = new IPStatus();
                    try
                    {
                        Ping p = new Ping();
                        PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                        status = pr.Status;
                    }
                    catch { }
                    if (status == IPStatus.Success)
                    {

                    }
                    else
                    {
                        MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                        //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                    }


                    if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                    {
                        //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                        PhoneCleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                    }
                    //StatysLabel.Text = "";
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";

                }
                else if (frmClean.cCfg.CheckType == "fiomatch_1")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходный ФИО) не найден!!!!", "Внимание",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Warning);
                        return;
                    }


                    IPStatus status = new IPStatus();
                    try
                    {
                        Ping p = new Ping();
                        PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                        status = pr.Status;
                    }
                    catch { }
                    if (status == IPStatus.Success)
                    {

                    }
                    else
                    {
                        MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                        //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                    }


                    if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                    {
                        //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                    }
                    //StatysLabel.Text = "";
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";

                }
                else if (frmClean.cCfg.CheckType == "fiomatch_2")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходный ФИО) не найден!!!!", "Внимание",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Warning);
                        return;
                    }


                    IPStatus status = new IPStatus();
                    try
                    {
                        Ping p = new Ping();
                        PingReply pr = p.Send(@"http://77.95.202.185:7778/");
              
                        status = pr.Status;
                    }
                    catch { }
                    if (status == IPStatus.Success)
                    {

                    }
                    else
                    {
                        MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                        //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                    }


                    if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                    {
                        //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                    }
                    //StatysLabel.Text = "";
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";

                }else if (frmClean.cCfg.CheckType == "addrmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkAddress" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Warning);
                        return;
                    }

                    IPStatus status = new IPStatus();
                    try
                    {
                        Ping p = new Ping();
                        PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                        status = pr.Status;
                    }
                    catch { }
                    if (status == IPStatus.Success)
                    {

                    }
                    else
                    {
                        MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                        //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                    }

                   // if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                   // {
                        //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";


                        DataView MyDataView = new DataView(((frmMine)this.Owner).dtMain);
                        CleanRow(MyDataView[cCfg.StartRow], cCfg.Ind, SaveResult, UseService);
                       // CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                    //}
                }
             else if (frmClean.cCfg.CheckType == "choose_addrmatch")
             {
                 foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                 {
                     if ("iqWorkAddress" == col.ColumnName)
                     {
                         cCfg.Ind = cCfgIndNum;
                     }
                     cCfgIndNum += 1;
                 }

                 if (cCfg.Ind == -1)
                 {
                     MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                     MessageBoxButtons.OK,
                                                     MessageBoxIcon.Warning);
                     return;
                 }

                 IPStatus status = new IPStatus();
                 try
                 {
                     Ping p = new Ping();
                     PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                     status = pr.Status;
                 }
                 catch { }
                 if (status == IPStatus.Success)
                 {

                 }
                 else
                 {
                     MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                     //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                 }

                 if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                 {
                     //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";

                     DataView MyDataView = new DataView(((frmMine)this.Owner).dtMain);
                     CleanRow(MyDataView[cCfg.StartRow], cCfg.Ind);
                     //CleanRow(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow][cCfg.Ind], cCfg.Ind);
                 }
             }
             else if (frmClean.cCfg.CheckType == "orgdublmatch")
             {
                 foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                 {
                     if ("iqWorkFullName" == col.ColumnName)
                     {
                         cCfg.Ind = cCfgIndNum;
                     }
                     cCfgIndNum += 1;
                 }

                 if (cCfg.Ind == -1)
                 {
                     MessageBox.Show("iqWorkFullName (Исходная организация) не найдена!!!!", "Внимание",
                                                       MessageBoxButtons.OK,
                                                       MessageBoxIcon.Warning);
                     return;
                 }


                 IPStatus status = new IPStatus();
                 try
                 {
                     Ping p = new Ping();
                     PingReply pr = p.Send(@"http://77.95.202.185:7778/");

                     status = pr.Status;
                 }
                 catch { }
                 if (status == IPStatus.Success)
                 {

                 }
                 else
                 {
                     MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                     //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";

                 }


                 if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count)
                 {
                     //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                     CheckOrgDublCleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                 }
                 //StatysLabel.Text = "";
                 cCfg.StartRow = 0;
                 cCfg.FuncType = "select";

                
             }

            //StatysLabel.Text = "";
            cCfg.StartRow = 0;
            cCfg.FuncType = "select";


        }

        public void ChangeVariant(int grdVariantRow)
        {
            cCfg.StartRow = grdVariantRow;
            if (cCfg.StartRow == 0)
            {


            }

            ((frmMine)this.Owner).dtVariant.Rows.Clear();

            int cCfgIndNum = 0;
            cCfg.Ind = -1;

            foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
            {
                if ("iqWorkAddress" == col.ColumnName)
                {
                    cCfg.Ind = cCfgIndNum;
                }
                if ("iqWorkEmail" == col.ColumnName)
                {
                    cCfg.Ind = cCfgIndNum;
                    
                }
                cCfgIndNum += 1;
            }

            if (cCfg.Ind == -1)
            {
                MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                  MessageBoxButtons.OK,
                                                  MessageBoxIcon.Warning);
                return;
            }

            IPStatus status = new IPStatus();
            try
            {
                Ping p = new Ping();
                PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                status = pr.Status;
            }
            catch { }
            if (status == IPStatus.Success)
            {

            }
            else
            {
                MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                //StatysLabel.Text = "Проверте Ваше соединение с Интернет!" + "\r\n";
            }

      
            if (cCfg.StartRow <= ((DataView)grdMain.Grid.DataSource).Count - 1 && cCfg.CheckType == "emailmatch")
            {
                //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                cCfg.StartRow += 1;
            }
            else
            {
                //StatysLabel.Text = "Обработка " + (cCfg.StartRow + 1).ToString() + " строки...";
                CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
                cCfg.StartRow += 1;
            }
            //StatysLabel.Text = ""; 

            cCfg.StartRow = 0;

        }
              
        public void Open(){
            string filename="";
            
            if (((frmMine)this.Owner).cfg.fileName == "")
            {
                OpenFileDialog dlg = new OpenFileDialog();

                dlg.InitialDirectory = ((frmMine)this.Owner).cfg.TmpDir;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    filename = dlg.FileName;
                }
                else return;
            

            }else{
            filename=(((frmMine)this.Owner).cfg.TmpDir + "/" + ((frmMine)this.Owner).cfg.fileName + ".CSV");
            
            }
            filename = filename.Replace("_clean.", ".");
            filename = filename.Replace("_var.", ".");
            ((frmMine)this.Owner).cfg.fileName = filename;

            ((frmMine)this.Owner).OpenTextFile(filename.Replace(".", "_clean."), ((frmMine)this.Owner).dtMain, cmbCode.Text);
            ((frmMine)this.Owner).OpenTextFile(filename.Replace(".", "_var."), ((frmMine)this.Owner).dtVariant, cmbCode.Text);
            LoadForm();

            
        }

        private void btnOprn_Click(object sender, EventArgs e)
        {
            Open();
        }

        public void pause(bool go=false)
        {
           
            while (go)
            {
            }
        }

        public class cleanCfg
        {
            public int StartRow { get; set; }
            public int Ind { get; set; }
            public int StartInd { get; set; }
            public int StartUpdateCol { get; set; }
            public int NumItem { get; set; }
            public int LastSelectedRow { get; set; }
            public string FuncType { get; set; }
            public string LastFileName { get; set; }
            public string LastFilePath { get; set; }
            public int LastFileIndex { get; set; }
            public bool chKov { get; set; }
            public bool isWork { get; set; }
            public bool isPause { get; set; }
            public string IsUseIndex { get; set; }
            public bool isCleanAutoStart { get; set; }
            public int ErrorRowIndex { get; set; }
            public int AddrFullAddressCompareIndex { get; set; }
            public string AppPath { get; set; }
            public string CheckType { get; set; }
            public int nAll { get; set; }
            public int nGood { get; set; }
            public int nBad { get; set; }
            public int nSomn { get; set; }
        }


        public static cleanCfg cCfg = new cleanCfg
        {
            StartRow = 0,
            NumItem = 0,
            Ind = -1,
            StartInd = -1,
            StartUpdateCol = -1,
            LastSelectedRow = 0,
            FuncType = "select",
            LastFileName = "",
            LastFilePath = "",
            LastFileIndex = 2,
            chKov = false,
            isWork = false,
            isPause = false,
            IsUseIndex = "false",
            isCleanAutoStart = false,
            ErrorRowIndex = -1,
            AddrFullAddressCompareIndex = 0,
            AppPath = Application.StartupPath,
            CheckType = "none",
            nAll = 0,
            nGood = 0,
            nBad = 0,
            nSomn = 0

        };

        private void grdVariant_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void grdVariant_DoubleClick(object sender, EventArgs e)
        {
          
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ((frmMine)this.Owner).cfg.Filter = ((DataView)grdMain.Grid.DataSource).RowFilter;

            frmExport frm = new frmExport();
            frm.Owner = ((frmMine)this.Owner);
            frm.Show();
          
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

        }

        private void grdMain_BindingContextChanged(object sender, EventArgs e)
        {
           
        }

        private void prgBar_EnabledChanged(object sender, EventArgs e)
        {
   
        }

        private void frmClean_Load(object sender, EventArgs e)
        {

        }
        private void frmClean_Closing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Вы уверены, что хотите закрыть окно чистки?\nВернуться к чистке Вы можете из главного меню, пункт Функционал => Загрузка сохраннёного файла", "Внимание", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.Cancel)
                 e.Cancel=true;
        }

        private void frmClean_Activated(object sender, EventArgs e)
        {
            //this.TopMost = true;
        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {
        }

        private void grdColumns_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        }


        public void ChooseAddrClean(string AddrNew)
       {
           var cCfgIndNum = 0;
           cCfg.FuncType = "update";

            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqWorkAddress", AddrNew);
            OneRowClean(cCfg.LastSelectedRow,false);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isChanget", true);

               ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isChanget", true);
               cCfgIndNum += 1;


       }

        private void grdMain_Load(object sender, EventArgs e)
        {
            
        }

        
        private void prgBar_Click(object sender, EventArgs e)
        {

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        public void btnCancel_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Вы желаете прервать чистку? ", "Внимание",
                                                     MessageBoxButtons.YesNo,
                                                     MessageBoxIcon.Question);
            if (result == DialogResult.No)
            {
                cCfg.isWork = true;
                cCfg.ErrorRowIndex = -1;
            }
            else
            {
                cCfg.isWork = false;
                cCfg.isPause = true;
                cCfg.FuncType = "select";
                cCfg.ErrorRowIndex = cCfg.StartRow - 1;
                //cCfg.StartRow = 0;
                btnCancel.Visible = false;
                StatysLabel.Visible = false;
                btnStartCleaner.Enabled = true;
                dbtnFil.Enabled = true;
                toolStripDropDownButton1.Enabled = true;
                btnSave.Enabled = true;

            }
                             
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        public void IsBad_Click()
        {
            //changeStatusLabel(((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).Cells["textStatus"].Value.ToString(), "Плохой");
            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow]["textStatus"].ToString(), "Плохой");

            //((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", false);
            //((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", true);
            //((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightPink;
            //((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].Table..DefaultCellStyle.BackColor = Color.LightGreen;
            string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
            DataView dv = new DataView(((frmMine)this.Owner).dtMain);
            SQLiteData.UpdateRow(dv[cCfg.LastSelectedRow], TabName);

            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 3));


        }

        private void toolStripSplitButton_StatusFilter_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //toolStripSplitButton_StatusFilter.Image = toolStripSplitButton_StatusFilter.DropDownItems.
        }

        private void toolStripSplitButton_StatusFilter_ButtonClick(object sender, EventArgs e)
        {
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%%'";         
            }
        }

        private void toolStripMenuItem_good_Click(object sender, EventArgs e)
        {
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Хороший%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Хороший%'";

            }
            int tmpGood = ((DataView)grdMain.Grid.DataSource).Table.Rows.Count;
            Console.WriteLine("{0}", tmpGood);
        }

        private void toolStripMenuItem_somn_Click(object sender, EventArgs e)
        {
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Сомнительный%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Сомнительный%'";
            }
        }

        private void toolStripMenuItem_bad_Click(object sender, EventArgs e)
        {
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Плохой%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Плохой%'";
            }
        }

        public void IsGood_Click()
        {
            //changeStatusLabel(((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).Cells["textStatus"].Value.ToString(), "Хороший");
            changeStatusLabel(((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow]["textStatus"].ToString(), "Хороший");

            string AddrStringStr = fCl.textBox2.Text;

            if (fCl.textBox4.Text != "") AddrStringStr += ", дом " + fCl.textBox4.Text;
            if (fCl.textBox5.Text != "") AddrStringStr += ", кор. " + fCl.textBox5.Text;
            if (fCl.textBox7.Text != "") AddrStringStr += ", стр. " + fCl.textBox7.Text;
            if (fCl.textBox9.Text != "") AddrStringStr += ", лит. " + fCl.textBox9.Text;
            if (fCl.textBox6.Text != "") AddrStringStr += ", влад. " + fCl.textBox6.Text;
            if (fCl.textBox8.Text != "") AddrStringStr += ", уч. " + fCl.textBox8.Text;
            if (fCl.textBox10.Text != "") AddrStringStr += ", блок " + fCl.textBox10.Text;
            if (fCl.textBox11.Text != "") AddrStringStr += ", пав. " + fCl.textBox11.Text;
            if (fCl.textBox12.Text != "") AddrStringStr += ", офис " + fCl.textBox12.Text;
            if (fCl.textBox13.Text != "") AddrStringStr += ", кв. " + fCl.textBox13.Text;
            if (fCl.textBox16.Text != "") AddrStringStr += ", ком. " + fCl.textBox16.Text;
            if (fCl.textBox17.Text != "") AddrStringStr += ", вч " + fCl.textBox17.Text;
            if (fCl.textBox18.Text != "") AddrStringStr += ", а/я " + fCl.textBox18.Text;
            if (fCl.textBox19.Text != "") AddrStringStr += ", каб " + fCl.textBox19.Text;

            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqPostCode", fCl.textBox21.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqFullAddress", fCl.textBox2.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqHouse", fCl.textBox4.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqCase", fCl.textBox5.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqBuild", fCl.textBox7.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqLiter", fCl.textBox9.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqVlad", fCl.textBox6.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqBlock", fCl.textBox10.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqPav", fCl.textBox11.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqUch", fCl.textBox8.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqFlat", fCl.textBox13.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqKom", fCl.textBox16.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqOffice", fCl.textBox12.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqKab", fCl.textBox19.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqAbon", fCl.textBox18.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqVch", fCl.textBox17.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqLostAddr", fCl.textBox14.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqComment", fCl.textBox23.Text);
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("iqWorkAddress", AddrStringStr);

            fCl.textBox1.Text = AddrStringStr;

            string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
           // SQLiteData.UpdateRow((DataView)((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow], TabName);
           // DataRowView drv = ((frmMine)this.Owner).dtMain.DefaultView[((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow]];
            //((DataRowView)DataGridViewRow.DataBoundItem).Row
            DataView dv = new DataView(((frmMine)this.Owner).dtMain);
            SQLiteData.UpdateRow(dv[cCfg.LastSelectedRow], TabName);

            fCl.label_good.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 1));
            fCl.label_bad.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 2));
            fCl.label_somn.Text = Convert.ToString(SQLiteData.GetRecordCount(TabName, 3));
            
        }

        public void changeStatusLabel(string were, string that, int ChangetRowNum  = -1)
        {
            if (were == "Плохой" && that == "Хороший")
            {
                //nBad -= 1;
                //label_bad.Text = nBad.ToString();
                //fCl.label_bad.Text = nBad.ToString();
                //cCfg.nBad = nBad;

                //nGood += 1;
                //label_good.Text = nGood.ToString();
                //fCl.label_good.Text = nGood.ToString();
                //cCfg.nGood = nGood;

                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                if (ChangetRowNum == -1)
                {
                    //((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                    if (grdMain.Grid.CurrentRow != null)
                        ((DataGridViewRow)grdMain.Grid.CurrentRow).DefaultCellStyle.BackColor = Color.LightGreen;
                }
                else
                {
                    ((DataGridViewRow)grdMain.Grid.Rows[ChangetRowNum]).DefaultCellStyle.BackColor = Color.LightGreen;
                }
                
            }

            if (string.IsNullOrEmpty(were) && that == "Хороший")
            {
                               
                //nGood += 1;
                //label_good.Text = nGood.ToString();
                //fCl.label_good.Text = nGood.ToString();
                //cCfg.nGood = nGood;

                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                if (grdMain.Grid.CurrentRow != null)
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightGreen;
            }

            if (were == "Сомнительный" && that == "Хороший")
            {
                //nSomn -= 1;
                //label_somn.Text = nSomn.ToString();
                //fCl.label_somn.Text = nSomn.ToString();
                //cCfg.nSomn = nSomn;

                //nGood += 1;
                //label_good.Text = nGood.ToString();
                //fCl.label_good.Text = nGood.ToString();
                //cCfg.nGood = nGood;

                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                //((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightGreen;
                if (grdMain.Grid.CurrentRow != null  )
                    ((DataGridViewRow)grdMain.Grid.CurrentRow).DefaultCellStyle.BackColor = Color.LightGreen;
            }

            if (were == "Хороший" && that == "Плохой")
            {
                //nBad += 1;
                //label_bad.Text = nBad.ToString();
                //fCl.label_bad.Text = nBad.ToString();
                //cCfg.nBad = nBad;

                //nGood -= 1;
                //label_good.Text = nGood.ToString();
                //fCl.label_good.Text = nGood.ToString();
                //cCfg.nGood = nGood;

                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                //((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightPink;
                if (grdMain.Grid.CurrentRow != null)
                    ((DataGridViewRow)grdMain.Grid.CurrentRow).DefaultCellStyle.BackColor = Color.LightPink;
            }

            if (string.IsNullOrEmpty(were) && that == "Плохой")
            {
                //nBad += 1;
                //label_bad.Text = nBad.ToString();
                //fCl.label_bad.Text = nBad.ToString();
                //cCfg.nBad = nBad;
              
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                if (grdMain.Grid.CurrentRow != null)
                    ((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightPink;
            }

            if (were == "Хороший" && that == "Сомнительный")
            {
                //nSomn += 1;
                //label_somn.Text = nSomn.ToString();
                //fCl.label_somn.Text = nSomn.ToString();
                //cCfg.nSomn = nSomn;

                //nGood -= 1;
                //label_good.Text = nGood.ToString();
                //fCl.label_good.Text = nGood.ToString();
                //cCfg.nGood = nGood;
            }

            if (were == "Плохой" && that == "Сомнительный")
            {
                //nSomn += 1;
                //label_somn.Text = nSomn.ToString();
                //fCl.label_somn.Text = nSomn.ToString();
                //cCfg.nSomn = nSomn;

                //nBad -= 1;
                //label_bad.Text = nBad.ToString();
                //fCl.label_bad.Text = nBad.ToString();
                //cCfg.nBad = nBad;
            }

            if (were == "Сомнительный" && that == "Плохой")
            {
                //nSomn -= 1;
                //label_somn.Text = nSomn.ToString();
                //fCl.label_somn.Text = nSomn.ToString();
                //cCfg.nSomn = nSomn;

                //nBad += 1;
                //label_bad.Text = nBad.ToString();
                //fCl.label_bad.Text = nBad.ToString();
                //cCfg.nBad = nBad;

                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isCheck", false);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isBad", true);
                ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("textStatus", that);
                //((DataGridViewRow)grdMain.Grid.Rows[cCfg.LastSelectedRow]).DefaultCellStyle.BackColor = Color.LightPink;
                if (grdMain.Grid.CurrentRow != null)
                    ((DataGridViewRow)grdMain.Grid.CurrentRow).DefaultCellStyle.BackColor = Color.LightPink;
            }
            ((frmMine)this.Owner).dtMain.Rows[cCfg.LastSelectedRow].SetField("isChanget", true);

            this.toolStripStatusLabel1.Text = "Всего выбрано " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

        }

        private void checkBox_IsUseIndex_CheckedChanged(object sender, EventArgs e)
        {
            aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\settings.ini");
            cCfg.IsUseIndex = oIni.ReadValue("CleanOpt", "IsUseIndex", "false");
            cCfg.IsUseIndex = oIni.ReadValue("CleanOpt", "IsUseIndex", "false");
        }

        public bool UseIndexCheck(string inIndex ="", string iqIndex = "")
        {
            bool UseIndexChecked = false;
            return UseIndexChecked;
        }

        private void btnStartCleaner_MouseHover(object sender, EventArgs e)
        {


        }

        public bool isValidMail(string e_mail = "")
        {
            string pattern = "[.\\-_a-z0-9]+@([a-z0-9][\\-a-z0-9]+\\.)+[a-z]{2,6}";
            string input = e_mail;

            bool isMatch = false;
            string status = " не E-Mail!";

            foreach (Match field in Regex.Matches(input, pattern))
            {
                isMatch = true;
                status = " E-Mail!";
            }
            return isMatch;
        }

        private void ed_c_message_TextChanged(object sender, EventArgs e)
        {

        }

 

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
  
            }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }


        public void CleabFileThread(object sender, DoWorkEventArgs e)
        {

            if (ABDLight.Properties.Settings.Default.Login == "" || ABDLight.Properties.Settings.Default.edPwd == "")
            {

                MessageBox.Show("Вы не верно указали логин или пароль! Повторите ввод!", "Внимание",
                                                      MessageBoxButtons.OK,
                                                      MessageBoxIcon.Error);

                this.Close();
                return;
            }

            this.Invoke((MethodInvoker)delegate
            {


                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Count.ToString();
                /////////////////////////////////////////////

                int cCfgIndNum = 0;
                cCfg.Ind = -1;


                //fiomatch_1

                if (frmClean.cCfg.CheckType == "fiomatch_1")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходное ФИО) не найдено!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //



                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "ФИО разобраны!";
                    MessageBox.Show("ФИО разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }

                //fiomatch_2

                if (frmClean.cCfg.CheckType == "fiomatch_2")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходное ФИО) не найдено!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "ФИО разобраны!";
                    MessageBox.Show("ФИО разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }

                if (frmClean.cCfg.CheckType == "emailmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkEmail" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkEmail (Исходный Email) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }




                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        EmailCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Адреса разобраны!";
                    MessageBox.Show("Адреса разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }


                if (frmClean.cCfg.CheckType == "phonematch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkPhone" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkPhone (Исходный Телефон) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }


                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        PhoneCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Телефоны разобраны!";
                    MessageBox.Show("Телефоны разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    btnStartCleaner.Text = "Начать чистку заново";
                    return;
                }
                else
                    if (frmClean.cCfg.CheckType == "orgdublmatch")
                    {
                        foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                        {
                            if ("iqWorkFullName" == col.ColumnName)
                            {
                                cCfg.Ind = cCfgIndNum;
                            }
                            cCfgIndNum += 1;
                        }

                        if (cCfg.Ind == -1)
                        {
                            MessageBox.Show("iqWorkFullName (Исходная организация) не найдена!!!!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Warning);
                            return;
                        }


                        //Параметры:
                        //Разные
                        btnCancel.Visible = true;
                        StatysLabel.Visible = true;
                        cCfg.isWork = true;
                        cCfg.FuncType = "add";

                        //

                        for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                        {

                            if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                            {
                                this.btnStartCleaner.Text = "Продолжить чистку!";
                                i = cCfg.ErrorRowIndex + 1;
                                cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                                cCfg.ErrorRowIndex = -1;
                            }
                            else if (cCfg.isPause)
                            {
                                this.btnStartCleaner.Text = "Продолжить чистку!";
                                i = cCfg.ErrorRowIndex - 1;
                                cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                                cCfg.ErrorRowIndex = -1;
                                cCfg.isPause = false;
                            }

                            toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                            CheckOrgDublCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                            cCfg.StartRow += 1;
                            lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                            if (!cCfg.isWork)
                            {

                                cCfg.FuncType = "select";
                                cCfg.ErrorRowIndex = cCfg.StartRow;
                                cCfg.StartRow = 0;
                                btnCancel.Visible = false;
                                StatysLabel.Visible = false;
                                btnStartCleaner.Text = "Продолжить чистку!";
                                this.Close();
                                return;
                            }

                            Application.DoEvents();
                        }
                        //((frmMine)this.Owner).dtVariant.Rows.Clear();
                        cCfg.StartRow = 0;
                        cCfg.FuncType = "select";
                        btnCancel.Visible = false;
                        StatysLabel.Visible = false;

                        //StatysLabel.Text = "Организации разобраны!";
                        MessageBox.Show("Организации разобраны!", "Внимание",
                                                                  MessageBoxButtons.OK,
                                                                  MessageBoxIcon.Information);
                        //StatysLabel.Text = "";
                        cCfg.ErrorRowIndex = -1;
                        return;
                    }
                    else
                        if (frmClean.cCfg.CheckType == "emailmatch")
                        {
                            foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                            {
                                if ("iqWorkEmail" == col.ColumnName)
                                {
                                    cCfg.Ind = cCfgIndNum;
                                }
                                cCfgIndNum += 1;
                            }

                            if (cCfg.Ind == -1)
                            {
                                MessageBox.Show("iqWorkEmail (Исходный Email) не найден!!!!", "Внимание",
                                                                  MessageBoxButtons.OK,
                                                                  MessageBoxIcon.Warning);
                                return;
                            }

                            btnCancel.Visible = true;
                            StatysLabel.Visible = true;
                            cCfg.isWork = true;
                            cCfg.FuncType = "add";

                            for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                            {
                                if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                                {
                                    this.btnStartCleaner.Text = "Продолжить чистку!";
                                    i = cCfg.ErrorRowIndex + 1;
                                    cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                                    cCfg.ErrorRowIndex = -1;
                                }
                                else if (cCfg.isPause)
                                {
                                    this.btnStartCleaner.Text = "Продолжить чистку!";
                                    i = cCfg.ErrorRowIndex - 1;
                                    cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                                    cCfg.ErrorRowIndex = -1;
                                    cCfg.isPause = false;
                                }

                                toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                                EmailCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                                cCfg.StartRow += 1;
                                lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                                if (!cCfg.isWork)
                                {

                                    cCfg.FuncType = "select";
                                    cCfg.ErrorRowIndex = cCfg.StartRow;
                                    cCfg.StartRow = 0;
                                    btnCancel.Visible = false;
                                    StatysLabel.Visible = false;
                                    btnStartCleaner.Text = "Продолжить чистку!";
                                    this.Close();
                                    return;
                                }
                                Application.DoEvents();
                            }
                            //((frmMine)this.Owner).dtVariant.Rows.Clear();
                            cCfg.StartRow = 0;
                            cCfg.FuncType = "select";
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;

                            //StatysLabel.Text = "Адреса разобраны!";
                            MessageBox.Show("Адреса разобраны!", "Внимание",
                                                                      MessageBoxButtons.OK,
                                                                      MessageBoxIcon.Information);
                            //StatysLabel.Text = "";
                            cCfg.ErrorRowIndex = -1;
                            return;
                        }
                        else
                            if (frmClean.cCfg.CheckType == "choose_addrmatch")
                            {
                                foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                                {
                                    if ("iqWorkAddress" == col.ColumnName)
                                    {
                                        cCfg.Ind = cCfgIndNum;
                                    }
                                    cCfgIndNum += 1;
                                }
                                if (cCfg.Ind == -1)
                                {
                                    MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                                      MessageBoxButtons.OK,
                                                                      MessageBoxIcon.Warning);
                                    return;
                                }


                                IPStatus status = new IPStatus();
                                try
                                {

                                    Ping p = new Ping();
                                    PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                                    status = pr.Status;
                                }
                                catch { }
                                if (status == IPStatus.Success)
                                {
                                    //MessageBox.Show("Соединение с сервером установлено! Начинаю чистку.");
                                    //StatysLabel.Text = "Соединение с сервером установлено! Начинаю чистку.";
                                }
                                else
                                {
                                    MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                                    //StatysLabel.Text = "Соединение с сервером не установлено! Начинаю чистку.";
                                }

                                btnCancel.Visible = true;
                                StatysLabel.Visible = true;
                                cCfg.isWork = true;
                                cCfg.FuncType = "add";

                                for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                                {
                                    if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                                    {
                                        this.btnStartCleaner.Text = "Продолжить чистку!";
                                        i = cCfg.ErrorRowIndex + 1;
                                        cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                                        cCfg.ErrorRowIndex = -1;
                                    }
                                    else if (cCfg.isPause)
                                    {
                                        this.btnStartCleaner.Text = "Продолжить чистку!";
                                        i = cCfg.ErrorRowIndex - 1;
                                        cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                                        cCfg.ErrorRowIndex = -1;
                                        cCfg.isPause = false;
                                    }

                                    toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                                    CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                                    cCfg.StartRow += 1;
                                    lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                                    if (!cCfg.isWork)
                                    {

                                        cCfg.FuncType = "select";
                                        cCfg.ErrorRowIndex = cCfg.StartRow;
                                        cCfg.StartRow = 0;
                                        btnCancel.Visible = false;
                                        StatysLabel.Visible = false;
                                        btnStartCleaner.Text = "Продолжить чистку!";
                                        this.Close();
                                        return;
                                    }


                                    // ((frmMine)this.Owner).dtVariant.Rows.Clear();

                                    Application.DoEvents();
                                }
                                //((frmMine)this.Owner).dtVariant.Rows.Clear();
                                cCfg.StartRow = 0;
                                cCfg.FuncType = "select";
                                btnCancel.Visible = false;
                                StatysLabel.Visible = false;

                                //StatysLabel.Text = "Организации разобраны!";
                                MessageBox.Show("Организации разобраны!", "Внимание",
                                                                          MessageBoxButtons.OK,
                                                                          MessageBoxIcon.Information);
                                //StatysLabel.Text = "";
                                cCfg.ErrorRowIndex = -1;
                                return;
                            }
                            else
                                if (frmClean.cCfg.CheckType == "addrmatch")
                                {
                                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                                    {
                                        if ("iqWorkAddress" == col.ColumnName)
                                        {
                                            cCfg.Ind = cCfgIndNum;
                                        }
                                        cCfgIndNum += 1;
                                    }
                                    if (cCfg.Ind == -1)
                                    {
                                        MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                                          MessageBoxButtons.OK,
                                                                          MessageBoxIcon.Warning);
                                        return;
                                    }


                                    IPStatus status = new IPStatus();
                                    try
                                    {
                                        Ping p = new Ping();
                                        PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                                        status = pr.Status;
                                    }
                                    catch { }
                                    if (status == IPStatus.Success)
                                    {
                                        //MessageBox.Show("Соединение с сервером установлено! Начинаю чистку.");
                                        //StatysLabel.Text = "Соединение с сервером установлено! Начинаю чистку.";
                                    }
                                    else
                                    {
                                        MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                                        //StatysLabel.Text = "Соединение с сервером не установлено! Начинаю чистку.";
                                    }

                                    btnCancel.Visible = true;
                                    StatysLabel.Visible = true;
                                    btnStartCleaner.Enabled = false;
                                    dbtnFil.Enabled = false;
                                    toolStripDropDownButton1.Enabled = false;
                                    btnSave.Enabled = false;
                                    cCfg.isWork = true;
                                    cCfg.FuncType = "add";

                                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                                    {
                                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                                        {
                                            this.btnStartCleaner.Text = "Продолжить чистку!";
                                            i = cCfg.ErrorRowIndex + 1;
                                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                                            cCfg.ErrorRowIndex = -1;
                                        }
                                        else if (cCfg.isPause)
                                        {
                                            this.btnStartCleaner.Text = "Продолжить чистку!";
                                            i = cCfg.ErrorRowIndex - 1;
                                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                                            cCfg.ErrorRowIndex = -1;
                                            cCfg.isPause = false;
                                        }

                                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                                        CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                                        cCfg.StartRow += 1;
                                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";
                                     

                                        if (!cCfg.isWork)
                                        {

                                            cCfg.FuncType = "select";
                                            cCfg.ErrorRowIndex = cCfg.StartRow;
                                            cCfg.StartRow = 0;
                                            btnCancel.Visible = false;
                                            StatysLabel.Visible = false;
                                            btnStartCleaner.Text = "Продолжить чистку!";
                                            btnStartCleaner.Enabled = true;
                                            dbtnFil.Enabled = true;
                                            toolStripDropDownButton1.Enabled = true;
                                            btnSave.Enabled = true;
                                            //this.Close();
                                            //return;
                                        }

                                        Application.DoEvents();
                                        // ((frmMine)this.Owner).dtVariant.Rows.Clear();           
                                    }

                                }

                ((frmMine)this.Owner).dtVariant.Rows.Clear();
                cCfg.StartRow = 0;
                cCfg.FuncType = "select";
                btnCancel.Visible = false;
                StatysLabel.Visible = false;
                btnStartCleaner.Enabled = true;
                dbtnFil.Enabled = true;
                toolStripDropDownButton1.Enabled = true;
                btnSave.Enabled = true;


                //StatysLabel.Text = "";
                cCfg.ErrorRowIndex = -1;
            });

        }
        public void backgroundWorker_Service_DoWork(object sender, DoWorkEventArgs e)
        {
            if (ABDLight.Properties.Settings.Default.Login == "" || ABDLight.Properties.Settings.Default.edPwd == "")
            {

                MessageBox.Show("Вы не верно указали логин или пароль! Повторите ввод!", "Внимание",
                                                      MessageBoxButtons.OK,
                                                      MessageBoxIcon.Error);

                this.Close();
                return;
            }

            this.Invoke((MethodInvoker)delegate
            {

                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Count.ToString();
                /////////////////////////////////////////////

                int cCfgIndNum = 0;
                cCfg.Ind = -1;


                //fiomatch_1

                if (frmClean.cCfg.CheckType == "fiomatch_1")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходное ФИО) не найдено!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //



                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "ФИО разобраны!";
                    MessageBox.Show("ФИО разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }

                //fiomatch_2

                if (frmClean.cCfg.CheckType == "fiomatch_2")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFIO" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFIO (Исходное ФИО) не найдено!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        FIO1_CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "ФИО разобраны!";
                    MessageBox.Show("ФИО разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }

                if (frmClean.cCfg.CheckType == "emailmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkEmail" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkEmail (Исходный Email) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }




                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        EmailCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Адреса разобраны!";
                    MessageBox.Show("Адреса разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    btnStartCleaner.Text = "Начать чистку заново";
                    return;
                }


                if (frmClean.cCfg.CheckType == "phonematch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkPhone" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkPhone (Исходный Телефон) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }


                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        PhoneCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Телефоны разобраны!";
                    MessageBox.Show("Телефоны разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }
               else
                if (frmClean.cCfg.CheckType == "orgdublmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkFullName" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkFullName (Исходная организация) не найдена!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }


                    //Параметры:
                    //Разные
                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    //

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
  
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        CheckOrgDublCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }

                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Организации разобраны!";
                    MessageBox.Show("Организации разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }
                else
                if (frmClean.cCfg.CheckType == "emailmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkEmail" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }

                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkEmail (Исходный Email) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }

                    btnCancel.Visible = true;
                    StatysLabel.Visible = true;
                    cCfg.isWork = true;
                    cCfg.FuncType = "add";

                    for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                    {
                        if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex + 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                            cCfg.ErrorRowIndex = -1;
                        }
                        else if (cCfg.isPause)
                        {
                            this.btnStartCleaner.Text = "Продолжить чистку!";
                            i = cCfg.ErrorRowIndex - 1;
                            cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                            cCfg.ErrorRowIndex = -1;
                            cCfg.isPause = false;
                        }

                        toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                        EmailCleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                        cCfg.StartRow += 1;
                        lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                        if (!cCfg.isWork)
                        {

                            cCfg.FuncType = "select";
                            cCfg.ErrorRowIndex = cCfg.StartRow;
                            cCfg.StartRow = 0;
                            btnCancel.Visible = false;
                            StatysLabel.Visible = false;
                            btnStartCleaner.Text = "Продолжить чистку!";
                            this.Close();
                            return;
                        }
                        Application.DoEvents();
                    }
                    //((frmMine)this.Owner).dtVariant.Rows.Clear();
                    cCfg.StartRow = 0;
                    cCfg.FuncType = "select";
                    btnCancel.Visible = false;
                    StatysLabel.Visible = false;

                    //StatysLabel.Text = "Адреса разобраны!";
                    MessageBox.Show("Адреса разобраны!", "Внимание",
                                                              MessageBoxButtons.OK,
                                                              MessageBoxIcon.Information);
                    //StatysLabel.Text = "";
                    cCfg.ErrorRowIndex = -1;
                    return;
                }
                else
                if (frmClean.cCfg.CheckType == "choose_addrmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkAddress" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }
                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }
                

                IPStatus status = new IPStatus();
                try
                {
                    
                    Ping p = new Ping();
                    PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                    status = pr.Status;
                }
                catch { }
                if (status == IPStatus.Success)
                {
                    //MessageBox.Show("Соединение с сервером установлено! Начинаю чистку.");
                    //StatysLabel.Text = "Соединение с сервером установлено! Начинаю чистку.";
                }
                else
                {
                    MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                    //StatysLabel.Text = "Соединение с сервером не установлено! Начинаю чистку.";
                }

                btnCancel.Visible = true;
                StatysLabel.Visible = true;
                cCfg.isWork = true;
                cCfg.FuncType = "add";

                for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                {
                    if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                    {
                        this.btnStartCleaner.Text = "Продолжить чистку!";
                        i = cCfg.ErrorRowIndex + 1;
                        cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                        cCfg.ErrorRowIndex = -1;
                    }
                    else if (cCfg.isPause)
                    {
                        this.btnStartCleaner.Text = "Продолжить чистку!";
                        i = cCfg.ErrorRowIndex - 1;
                        cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                        cCfg.ErrorRowIndex = -1;
                        cCfg.isPause = false;
                    }

                    toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();
                    CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                    cCfg.StartRow += 1;
                    lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                    if (!cCfg.isWork)
                    {

                        cCfg.FuncType = "select";
                        cCfg.ErrorRowIndex = cCfg.StartRow;
                        cCfg.StartRow = 0;
                        btnCancel.Visible = false;
                        StatysLabel.Visible = false;
                        btnStartCleaner.Text = "Продолжить чистку!";
                        this.Close();
                        return;
                    }
                
                    
                    // ((frmMine)this.Owner).dtVariant.Rows.Clear();

                         Application.DoEvents();
                    }
                        //((frmMine)this.Owner).dtVariant.Rows.Clear();
                        cCfg.StartRow = 0;
                        cCfg.FuncType = "select";
                        btnCancel.Visible = false;
                        StatysLabel.Visible = false;

                        //StatysLabel.Text = "Организации разобраны!";
                        MessageBox.Show("Организации разобраны!", "Внимание",
                                                                  MessageBoxButtons.OK,
                                                                  MessageBoxIcon.Information);
                        //StatysLabel.Text = "";
                        cCfg.ErrorRowIndex = -1;
                        return;
                }           
               else
                if (frmClean.cCfg.CheckType == "addrmatch")
                {
                    foreach (DataColumn col in ((frmMine)this.Owner).dtMain.Columns)
                    {
                        if ("iqWorkAddress" == col.ColumnName)
                        {
                            cCfg.Ind = cCfgIndNum;
                        }
                        cCfgIndNum += 1;
                    }
                    if (cCfg.Ind == -1)
                    {
                        MessageBox.Show("iqWorkAddress (Исходный адрес) не найден!!!!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Warning);
                        return;
                    }
                

                IPStatus status = new IPStatus();
                try
                {
                    Ping p = new Ping();
                    PingReply pr = p.Send(@"http://77.95.202.185:7778/");
                    status = pr.Status;
                }
                catch { }
                if (status == IPStatus.Success)
                {
                    //MessageBox.Show("Соединение с сервером установлено! Начинаю чистку.");
                    //StatysLabel.Text = "Соединение с сервером установлено! Начинаю чистку.";
                }
                else
                {
                    MessageBox.Show("Проверте Ваше соединение с Интернет!" + "\r\n");
                    //StatysLabel.Text = "Соединение с сервером не установлено! Начинаю чистку.";
                }

                btnCancel.Visible = true;
                btnStartCleaner.Enabled = false;
                dbtnFil.Enabled = false;
                toolStripDropDownButton1.Enabled = false;
                btnSave.Enabled = false;
                StatysLabel.Visible = true;
                cCfg.isWork = true;
                cCfg.FuncType = "add";

                for (var i = 0; i < ((DataView)grdMain.Grid.DataSource).Count; i += 1)
                {
                    if (cCfg.ErrorRowIndex != -1 && !cCfg.isPause)
                    {
                        this.btnStartCleaner.Text = "Продолжить чистку!";
                        i = cCfg.ErrorRowIndex + 1;
                        cCfg.StartRow = cCfg.ErrorRowIndex + 1;
                        //prgBar.Maximum = ((DataView)grdMain.Grid.DataSource).Count - cCfg.ErrorRowIndex + 1;
                        cCfg.ErrorRowIndex = -1;
                    }
                    else if (cCfg.isPause)
                    {
                        this.btnStartCleaner.Text = "Продолжить чистку!";
                        i = cCfg.ErrorRowIndex - 1;
                        cCfg.StartRow = cCfg.ErrorRowIndex - 1;
                        //prgBar.Maximum = ((DataView)grdMain.Grid.DataSource).Count - cCfg.ErrorRowIndex;
                        cCfg.ErrorRowIndex = -1;
                        cCfg.isPause = false;
                    }

                    toolStrip1.Text = ((DataView)grdMain.Grid.DataSource).Count.ToString();

                    cCfg.StartRow = Convert.ToInt32(grdMain.Grid.Rows[i].Cells["ID_IQ"].Value.ToString()) - 1;
                    CleanRow(((DataView)grdMain.Grid.DataSource)[i], cCfg.Ind);
                    //DataView MyDataView = new DataView(((frmMine)this.Owner).dtMain);
                    //CleanRow(MyDataView[cCfg.StartRow], cCfg.Ind);

                    cCfg.StartRow += 1;
                    lbValid.Text = "Всего обработано: " + (i + 1).ToString() + " строк";

                    if (!cCfg.isWork)
                    {

                        cCfg.FuncType = "select";
                        cCfg.ErrorRowIndex = cCfg.StartRow;
                        cCfg.StartRow = 0;
                        btnCancel.Visible = false;
                        StatysLabel.Visible = false;
                        btnStartCleaner.Text = "Продолжить чистку!";
                        btnStartCleaner.Enabled = true;
                        dbtnFil.Enabled = true;
                        toolStripDropDownButton1.Enabled = true;
                        btnSave.Enabled = true;
                        //this.Close();
                        return;
                    }

                    Application.DoEvents();
                    // ((frmMine)this.Owner).dtVariant.Rows.Clear();           
                }

                }

                ((frmMine)this.Owner).dtVariant.Rows.Clear();
                cCfg.StartRow = 0;
                cCfg.FuncType = "select";
                btnCancel.Visible = false;
                StatysLabel.Visible = false;
                this.btnStartCleaner.Enabled = true;
                dbtnFil.Enabled = true;
                toolStripDropDownButton1.Enabled = true;
                btnSave.Enabled = true;

                //StatysLabel.Text = "Адреса разобраны!";
                MessageBox.Show("Адреса разобраны!", "Внимание",
                                                          MessageBoxButtons.OK,
                                                          MessageBoxIcon.Information);
                //StatysLabel.Text = "";
                cCfg.ErrorRowIndex = -1;
                string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
                SQLiteData.ExecuteQuery("UPDATE t_TableInfo SET iqStartClean = " + cCfg.ErrorRowIndex + " where [Полный путь] = '" + TabName + "'");
                btnStartCleaner.Text = "Начать чистку заново";
            });  
  
        }

        private void backgroundWorker_Service_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            frmSaveDialog frm = new frmSaveDialog();
            frm.Owner = this;
            frm.ShowDialog();
            //if (frm.ShowDialog() == DialogResult.OK) this.Close();
            
        }

        private void toolStripButton_LoadFromDB_Click(object sender, EventArgs e)
        {
            Hashtable pars = new Hashtable();
            pars.Add("DB_Name", ABDLight.Properties.Settings.Default.DB);
            frmProgress.frm = new frmProgress();
            frmProgress.frm.Owner = Program.applicationContext.MainForm;
            frmProgress.frm.ExecuteCommand("OpenFromDB", pars);

           // cCfg.isWork = false;
            cCfg.StartRow = 0;
            cCfg.FuncType = "select";
            btnCancel.Visible = false;
            StatysLabel.Visible = false;


            //StatysLabel.Text = "";
            cCfg.ErrorRowIndex = -1;
            

        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox18_TextChanged(object sender, EventArgs e)
        {

        }

        private void exAll_Click(object sender, EventArgs e)
        {
            ((frmMine)this.Owner).cfg.Filter = "";

            frmExport frm = new frmExport();
            frm.Owner = ((frmMine)this.Owner);
            frm.Show();

        }

        private void exFilt_Click(object sender, EventArgs e)
        {
            ((frmMine)this.Owner).cfg.Filter = ((DataView)grdMain.Grid.DataSource).RowFilter;

            frmExport frm = new frmExport();
            frm.Owner = ((frmMine)this.Owner);
            frm.Show();
        }

        private void stAll_Click(object sender, EventArgs e)
        {
            /*
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%%'";         
            }*/
            FilterStatus = 0;

            Refilter();

        }

        private void stGood_Click(object sender, EventArgs e)
        {
            /*
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Хороший%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Хороший%'";

            }
            int tmpGood = ((DataView)grdMain.Grid.DataSource).Table.Rows.Count;
            Console.WriteLine("{0}", tmpGood);*/
            FilterStatus = 1;

            Refilter();

        }

        private void stSomn_Click(object sender, EventArgs e)
        {
            /*
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Сомнительный%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Сомнительный%'";
            }*/
            FilterStatus = 3;

            Refilter();

        }

        private void stBad_Click(object sender, EventArgs e)
        {
            /*
            if (((DataView)grdMain.Grid.DataSource).Table.Columns["textStatus"].DataType ==
                System.Type.GetType("System.String"))
            {
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Плохой%'";
                this.toolStripStatusLabel1.Text = "Всего загружено " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();

                //((frmMine)this.Owner).cfg.Filter = "textStatus like '%Плохой%'";
            }*/
            FilterStatus = 2;

            Refilter();

        }

        private void mnUsFilt_Click(object sender, EventArgs e)
        {
            frmFilter frm = new frmFilter();
            frm.Owner = this;
            frm.LoadForm(tblFilter,this.grdMain.Grid);
            frm.ShowDialog();
            Refilter();
            //((DataView)grdMain.Grid.DataSource).RowFilter = ((frmMine)this.Owner).cfg.Filter;

        }

        private void mnDefSet_Click(object sender, EventArgs e)
        {
            ((DataView)grdMain.Grid.DataSource).RowFilter = "";
            tblFilter.Clear();
            FilterStatus = 0;
            Refilter();
        }

        public void Refilter()
        {
            ((DataView)grdMain.Grid.DataSource).RowFilter = "";

            if (FilterStatus == 1)
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Хороший%'";
            if (FilterStatus == 2)
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Плохой%'";
            if (FilterStatus == 3)
                ((DataView)grdMain.Grid.DataSource).RowFilter = "textStatus like '%Сомнительный%'";

            foreach (DataRow row in tblFilter.Rows)
            {
                try
                {
                    string isFilEmp = "";
                    if (!string.IsNullOrEmpty(((DataView)grdMain.Grid.DataSource).RowFilter)) isFilEmp = " AND ";
                    //((frmClean)this.Owner).grdMain.Ro = isFilEmp + row[0].ToString() + row[1].ToString() + "'" + row[2].ToString() + "'";
                   if (row[1].ToString() == "=" || row[1].ToString() == "<" || row[1].ToString() == ">" || row[1].ToString() == "<>")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " " + row[1].ToString() + " '" + row[2].ToString() + "'";
                    if (row[1].ToString() == "Like" || row[1].ToString() == "not Like")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " " + row[1].ToString() + " '%" + row[2].ToString() + "%'";
                    if (row[1].ToString() == "is Null")
                        if (row[0].ToString() == "isCheck" ||row[0].ToString() == "isChanget"||row[0].ToString() == "isBad")
                            ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " = false";
                        else
                            ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " = ''";
                    if (row[1].ToString() == "is not Null")
                        if (row[0].ToString() == "isCheck" || row[0].ToString() == "isChanget" || row[0].ToString() == "isBad")
                            ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " = true";
                        else
                            ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " <> ''";
                    if (row[1].ToString() == "start with")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " like '" + row[2].ToString() + "%'";
                    if (row[1].ToString() == "no start with")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " not like '" + row[2].ToString() + "%'";
                    if (row[1].ToString() == "interval")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " >= '" + row[2].ToString().Substring(0,row[2].ToString().IndexOf("-")) + "' AND " + row[0].ToString() + " <= '" + row[2].ToString().Substring(row[2].ToString().IndexOf("-") + 1) + "'";
                    if (row[1].ToString() == "enumer")
                        ((DataView)grdMain.Grid.DataSource).RowFilter += isFilEmp + row[0].ToString() + " in ('" + row[2].ToString().Replace(",","','") + "')";
                }
                catch (Exception ex) { }

            }

            this.toolStripStatusLabel1.Text = "Всего выбрано " + ((DataView)grdMain.Grid.DataSource).Count.ToString() + " записей из " + ((DataView)grdMain.Grid.DataSource).Table.Rows.Count.ToString();


        }
        public void SelectOneRow(int StartRow)
        {
            //CleanRow(((DataView)grdMain.Grid.DataSource)[cCfg.StartRow], cCfg.Ind);
            //CleanRow(((frmMine)this.Owner).dtMain.Rows[cCfg.StartRow], cCfg.Ind);
            

            fCl.textBox1.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqWorkAddress"].ToString();
            fCl.cid.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["ID_IQ"].ToString();
            fCl.textBox21.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqPostCode"].ToString();
            fCl.textBox2.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqFullAddress"].ToString();
            fCl.textBox4.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqHouse"].ToString(); 
            fCl.textBox5.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqCase"].ToString(); 
            fCl.textBox7.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqBuild"].ToString(); 
            fCl.textBox9.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqLiter"].ToString(); 
            fCl.textBox6.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqVlad"].ToString();
            fCl.textBox8.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqUch"].ToString(); 
            fCl.textBox10.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqBlock"].ToString(); 
            fCl.textBox11.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqPav"].ToString(); 
            fCl.textBox12.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqOffice"].ToString();
            fCl.textBox13.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqFlat"].ToString();
            fCl.textBox16.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqKom"].ToString();
            fCl.textBox17.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqVch"].ToString(); 
            fCl.textBox18.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqAbon"].ToString(); 
            fCl.textBox19.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqKab"].ToString();
            fCl.textBox14.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqLostAddr"].ToString(); 
            fCl.textBox20.Text = ((DataView)grdMain.Grid.DataSource)[StartRow].Row["iqStatus"].ToString(); 
            fCl.textBox15.Text = "";

        }

        private void btnLoadAll_Click(object sender, EventArgs e)
        {
            ((frmMine)this.Owner).cfg.Filter = "";

            frmExport frm = new frmExport();
            frm.Owner = ((frmMine)this.Owner);
            frm.Show();
        }

        private void btnLoadCur_Click(object sender, EventArgs e)
        {
            ((frmMine)this.Owner).cfg.Filter = ((DataView)grdMain.Grid.DataSource).RowFilter;

            frmExport frm = new frmExport();
            frm.Owner = ((frmMine)this.Owner);
            frm.Show();
        }

        private void toolStripButton_ЫфмуЕщВИ_Click(object sender, EventArgs e)
        {

        }



        public void TreadClean()
        {
            //System.IO.File.AppendAllText("loginfo.txt", "Начало чистки "+System.DateTime.Now.ToLongTimeString()+"\r\n", Encoding.Unicode);


            isTreadCleanStop = null;

            var tasks = new List<Task>();
            ts = new CancellationTokenSource();
            ct = ts.Token;
            //var numberCores = 12;//Environment.ProcessorCount;
            int count = SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName);
            var numberCores = count < 100 ? count : 100;
            double dstep = Convert.ToDouble(count) / numberCores;
            int step = Convert.ToInt16(Math.Ceiling(dstep));

            

            string TabName = ABDLight.Properties.Settings.Default.CleanFileName;

            CleanInfo _CleanInfo = new CleanInfo();
            _CleanInfo.CleanFileName = ABDLight.Properties.Settings.Default.CleanFileName;
            _CleanInfo.FileName = ABDLight.Properties.Settings.Default.CleanFileName;
            _CleanInfo._Paramm.Count = count.ToString();
            _CleanInfo._Paramm.NumberCores = numberCores.ToString();


            string json = JsonConvert.SerializeObject(_CleanInfo);

            RecordCleanCount = new List<int>();
            for (int i = 0;i < numberCores;i++)
                RecordCleanCount.Add(0);

            string ColumnWhithAddress = "";
            int ii = 0;

            //SQLiteData.SetConnection();
            try
            {
                System.IO.Directory.CreateDirectory("temp");
                System.IO.Directory.CreateDirectory("temp\\info");
                System.IO.File.AppendAllText("temp\\info\\FileCleanInfo.csv", TabName + ";CheckAddressDetail\r\n", Encoding.Unicode);


                for (int i = 0; i < numberCores; i++)
                {
                    //SQLiteConnection sql_con_thread = new SQLiteConnection(string.Format("Data Source={0};", databaseName));
                    //sql_con_thread.Open();

                    int start, end;
                    start = i * step + 1;
                    if (i * step + step <= count)
                        end = i * step + step;
                    else
                        end = count;

                    var addr = new Dictionary<string, string>();
                    try
                    {
                        for (int j = start; j <= end; j++)
                        {
                            string ad = SQLiteData.GetAddrByID(TabName, j);
                            if(ad != "0")
                                addr.Add(j.ToString(), ad);
                        }
                    }
                    catch
                    {

                    }
                    //SQLiteData.CreateTable(((frmMine)this.Owner).dtMain, TabName + '_' + i.ToString());
                    //SQLiteData.TreadTable("TreadClean_" + i.ToString(), "Create", sql_con_thread);
                    int TreadNum = i;
                    var task = new Task(() => DoSomeLongWork(/*start, end,*/ TreadNum, addr, json), TaskCreationOptions.LongRunning);
                    
                    //task.Start();
                    tasks.Add(task);
                }

                foreach (Task task in tasks)
                {
                    task.Start();
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                  MessageBox.Show(ex.Message, "Ошибка при выполнении!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        //непосредственно DoSomeLongWork - то что мы выполняем
        void DoSomeLongWork(/*int start, int end,*/ int TreadNum, Dictionary<string, string> addrlist, string CleanInfo = "")
        {
            string conn;
            string res;

            //using (StreamWriter writeIn = new StreamWriter("temp\\Thread_" + TreadNum + ".csv"))
            //{
                //for (int i = start; i <= end; i++)
            foreach (KeyValuePair<string, string> item in addrlist)
                {
                    if (ct.IsCancellationRequested) break;

                    string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
                    conn = ABDLight.Properties.Settings.Default.Http + "/Services/IQDQ/SearchAddressDetail?addr=" + HttpUtility.UrlEncode(item.Value.ToString()) + "&login=" + HttpUtility.UrlEncode(ABDLight.Properties.Settings.Default.Login) + "&pwd=" + HttpUtility.UrlEncode(ABDLight.Properties.Settings.Default.edPwd);
                    //conn = ABDLight.Properties.Settings.Default.Http + "/Services/IQDQ/CheckAddress?addr=" + HttpUtility.UrlEncode(item.Value.ToString()) + "&login=" + HttpUtility.UrlEncode(ABDLight.Properties.Settings.Default.Login) + "&pwd=" + HttpUtility.UrlEncode(ABDLight.Properties.Settings.Default.edPwd);
                    //conn = "http://www.iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=" + addr + "&login=" + ABDLight.Properties.Settings.Default.Login + "&pwd=" + ABDLight.Properties.Settings.Default.edPwd;
                    try
                    {
                        res = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
                        //CleanResult.Add(start.ToString(), res);

                        Dictionary<string, string> ress = JSONObject.ParseAllJSON(res);

                        string AddressOtvet = "";
                        if (res.EndsWith("]"))
                        {
                            AddressOtvet = "{\"Address\":" + res + "}";
                        }
                        else if (res.EndsWith("}"))
                        {
                            AddressOtvet = "{\"Address\":[" + res + "]}";
                        }

                        //Проверка на бабло
                        foreach (KeyValuePair<string, string> itemRes in ress)
                        {
                            string field = itemRes.Key.Substring(0, itemRes.Key.IndexOf("_#_"));
                            if (field == "msg" &&
                                (itemRes.Value == "Уважаемый абонент у Вас закончился суточный лимит бесплатного использования сервиса!"
                                    || itemRes.Value == "Уважаемый абонент у Вас на счету закончились средства! Просим пополнить баланс Вашего лицевого счета"))
                            {
                                isTreadCleanStop = itemRes.Value;
                                if (ct.IsCancellationRequested) break;
                                ts.Cancel();
                                ((frmProgress)this.Parent).btnStopClean_Click(null, null);
                                //MessageBox.Show(itemRes.Value + "\nПосетите сайт http://iqdq.ru для пополнения Вашего счёта!\n", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }

                        //Проверка на бабло
                        
                        //if (AddressOtvet.IndexOf("Уважаемый абонент у Вас закончился суточный лимит бесплатного использования сервиса!") > -1
                        //     || AddressOtvet.IndexOf("Уважаемый абонент у Вас на счету закончились средства! Просим пополнить баланс Вашего лицевого счета")> -1)
                        //{
                        //    if (ct.IsCancellationRequested) break;
                        //    ts.Cancel();
                        //    MessageBox.Show(Address.Address[0].msg + "\nПосетите сайт http://iqdq.ru для пополнения Вашего счёта!\n", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        //    ((frmProgress)this.Parent).btnStopClean_Click(null, null);
                        //}

                        //SQLiteData.UpdateRowByJSON("TreadClean_" + TreadNum.ToString(), AddressOtvet, i.ToString());
                        //SQLiteData.TreadTable("TreadClean_" + TreadNum.ToString(), "Insert", sql_con_thread, i, AddressOtvet);

                        if (ct.IsCancellationRequested) break;
                        System.IO.File.AppendAllText("temp\\Thread_" + TreadNum + ".csv", item.Key.ToString() + ";" + AddressOtvet + "\r\n", Encoding.Unicode);
                        //string rows = i.ToString() + ";" + AddressOtvet;
                        //writeIn.WriteLine(rows);

                        //start++;
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("HAHA!!!\r\n" + ex.Message + "\r\n" + ex.ToString(), "Ошибка при выполнении!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
                    }
                    finally { RecordCleanCount[TreadNum] += 1;}
                }
            //}

        }

        public void TasksCanceled()
        {
            ts.Cancel();
        }

        public void GridEmptyHide()
        {
            for (int i = 0; i < grdMain.Grid.Columns.Count; i++)
            {
                if (grdMain.Grid.Rows.Count == 0)
                {
                    grdMain.Grid.Columns[i].Visible = true;
                }
                else
                {
                    int FieldVal = 0;
                    for (int j = 0; j < grdMain.Grid.Rows.Count; j++)
                        if (grdMain.Grid.Rows[j].Cells[i].Value.ToString() == "")
                            FieldVal++;

                    if (FieldVal == 0)
                        grdMain.Grid.Columns[i].Visible = true;
                    else
                        grdMain.Grid.Columns[i].Visible = false;
                }

            }
        }

        private void LoadFileFromDB(string TabName)
        {        
            ((frmMine)this.Owner).dtMain = SQLiteData.GetDataTable(TabName);

            ((frmMine)this.Owner).dtMain.Columns["isCheck"].Caption = "Прочищен";
            ((frmMine)this.Owner).dtMain.Columns["isChanget"].Caption = "Ручной разбор";
            ((frmMine)this.Owner).dtMain.Columns["isBad"].Caption = "Плохой";
            ((frmMine)this.Owner).dtMain.Columns["textStatus"].Caption = "Статус Разбора";
            ((frmMine)this.Owner).dtMain.Columns["iqWorkAddress"].Caption = "Полный разобранный адрес";
            ((frmMine)this.Owner).dtMain.Columns["iqPostCodeIn"].Caption = "Индекс исходного адреса";
            ((frmMine)this.Owner).dtMain.Columns["iqPostCode"].Caption = "Индекс разобранного адреса";
            ((frmMine)this.Owner).dtMain.Columns["iqFullAddress"].Caption = "Разобранный адрес";
            ((frmMine)this.Owner).dtMain.Columns["iqHouse"].Caption = "Дом";
            ((frmMine)this.Owner).dtMain.Columns["iqCase"].Caption = "Корпус";
            ((frmMine)this.Owner).dtMain.Columns["iqBuild"].Caption = "Строение";
            ((frmMine)this.Owner).dtMain.Columns["iqLiter"].Caption = "Литера";
            ((frmMine)this.Owner).dtMain.Columns["iqVlad"].Caption = "Владение";
            ((frmMine)this.Owner).dtMain.Columns["iqBlock"].Caption = "Блок";
            ((frmMine)this.Owner).dtMain.Columns["iqPom"].Caption = "Помещение";
            ((frmMine)this.Owner).dtMain.Columns["iqPav"].Caption = "Павильон";
            ((frmMine)this.Owner).dtMain.Columns["iqUch"].Caption = "Участок";
            ((frmMine)this.Owner).dtMain.Columns["iqObsch"].Caption = "Общежитие";
            ((frmMine)this.Owner).dtMain.Columns["iqFlat"].Caption = "Квартира";
            ((frmMine)this.Owner).dtMain.Columns["iqKom"].Caption = "Комната";
            ((frmMine)this.Owner).dtMain.Columns["iqOffice"].Caption = "Офис";
            ((frmMine)this.Owner).dtMain.Columns["iqKab"].Caption = "Кабинет";
            ((frmMine)this.Owner).dtMain.Columns["iqAbon"].Caption = "а/я";
            ((frmMine)this.Owner).dtMain.Columns["iqVch"].Caption = "в/ч";
            ((frmMine)this.Owner).dtMain.Columns["iqComment"].Caption = "Комментарий";
            ((frmMine)this.Owner).dtMain.Columns["iqKLADR"].Caption = "КЛАДР";
            ((frmMine)this.Owner).dtMain.Columns["iqLostAddr"].Caption = "Не разобрано";
            ((frmMine)this.Owner).dtMain.Columns["iqError"].Caption = "Ошибка";
            ((frmMine)this.Owner).dtMain.Columns["iqStatus"].Caption = "Статус";
            ((frmMine)this.Owner).dtMain.Columns["iqCountry"].Caption = "Страна";
            ((frmMine)this.Owner).dtMain.Columns["iqRegion"].Caption = "Регион";
            ((frmMine)this.Owner).dtMain.Columns["iqRegionType"].Caption = "Тип региона";
            ((frmMine)this.Owner).dtMain.Columns["iqSubRegion"].Caption = "Район";
            ((frmMine)this.Owner).dtMain.Columns["iqSubRegionType"].Caption = "Тип района";
            ((frmMine)this.Owner).dtMain.Columns["iqCity"].Caption = "Город";
            ((frmMine)this.Owner).dtMain.Columns["iqCityType"].Caption = "Тип города";
            ((frmMine)this.Owner).dtMain.Columns["iqNp"].Caption = "НП";
            ((frmMine)this.Owner).dtMain.Columns["iqNpType"].Caption = "Тип НП";
            ((frmMine)this.Owner).dtMain.Columns["iqStreet"].Caption = "Улица";
            ((frmMine)this.Owner).dtMain.Columns["iqStreetType"].Caption = "Тип улицы";




            ((frmMine)this.Owner).dtVariant.Clear();
            ((frmMine)this.Owner).dtVariant.Columns.Clear();

            DataColumn iqPostCode = new DataColumn();
            iqPostCode.ColumnName = "iqPostCode";
            iqPostCode.Caption = "Индекс разобранного адреса";
            iqPostCode.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqPostCode);

            DataColumn iqFullAddress = new DataColumn();
            iqFullAddress.ColumnName = "iqFullAddress";
            iqFullAddress.Caption = "Разобранный адрес";
            iqFullAddress.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqFullAddress);

            DataColumn iqHouse = new DataColumn();
            iqHouse.ColumnName = "iqHouse";
            iqHouse.Caption = "Дом";
            iqHouse.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqHouse);

            DataColumn iqCase = new DataColumn();
            iqCase.ColumnName = "iqCase";
            iqCase.Caption = "Корпус";
            iqCase.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqCase);

            DataColumn iqBuild = new DataColumn();
            iqBuild.ColumnName = "iqBuild";
            iqBuild.Caption = "Строение";
            iqBuild.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqBuild);

            DataColumn iqLiter = new DataColumn();
            iqLiter.ColumnName = "iqLiter";
            iqLiter.Caption = "Литера";
            iqLiter.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqLiter);

            DataColumn iqVlad = new DataColumn();
            iqVlad.ColumnName = "iqVlad";
            iqVlad.Caption = "Владение";
            iqVlad.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqVlad);

            DataColumn iqBlock = new DataColumn();
            iqBlock.ColumnName = "iqBlock";
            iqBlock.Caption = "Блок";
            iqBlock.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqBlock);

            DataColumn iqPom = new DataColumn();
            iqPom.ColumnName = "iqPom";
            iqPom.Caption = "Помещение";
            iqPom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqPom);

            DataColumn iqPav = new DataColumn();
            iqPav.ColumnName = "iqPav";
            iqPav.Caption = "Павильон";
            iqPav.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqPav);

            DataColumn iqUch = new DataColumn();
            iqUch.ColumnName = "iqUch";
            iqUch.Caption = "Участок";
            iqUch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqUch);

            DataColumn iqObsch = new DataColumn();
            iqObsch.ColumnName = "iqObsch";
            iqObsch.Caption = "Общежитие";
            iqObsch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqObsch);

            DataColumn iqFlat = new DataColumn();
            iqFlat.ColumnName = "iqFlat";
            iqFlat.Caption = "Квартира";
            iqFlat.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqFlat);
            //////////////////////////////////////////////////
            DataColumn iqKom = new DataColumn();
            iqKom.ColumnName = "iqKom";
            iqKom.Caption = "Комната";
            iqKom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqKom);

            DataColumn iqOffice = new DataColumn();
            iqOffice.ColumnName = "iqOffice";
            iqOffice.Caption = "Офис";
            iqOffice.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqOffice);

            DataColumn iqKab = new DataColumn();
            iqKab.ColumnName = "iqKab";
            iqKab.Caption = "Кабинет";
            iqKab.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqKab);

            DataColumn iqAbon = new DataColumn();
            iqAbon.ColumnName = "iqAbon";
            iqAbon.Caption = "а/я";
            iqAbon.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqAbon);

            DataColumn iqVch = new DataColumn();
            iqVch.ColumnName = "iqVch";
            iqVch.Caption = "в/ч";
            iqVch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqVch);

            DataColumn iqComment = new DataColumn();
            iqComment.ColumnName = "iqComment";
            iqComment.Caption = "Комментарий";
            iqComment.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqComment);

            DataColumn iqKLADR = new DataColumn();
            iqKLADR.ColumnName = "iqKLADR";
            iqKLADR.Caption = "КЛАДР";
            iqKLADR.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqKLADR);

            DataColumn iqLostAddr = new DataColumn();
            iqLostAddr.ColumnName = "iqLostAddr";
            iqLostAddr.Caption = "Не разобрано";
            iqLostAddr.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqLostAddr);

            DataColumn iqError = new DataColumn();
            iqError.ColumnName = "iqError";
            iqError.Caption = "Ошибка";
            iqError.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqError);

            DataColumn iqStatus = new DataColumn();
            iqStatus.ColumnName = "iqStatus";
            iqStatus.Caption = "Статус";
            iqStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqStatus);

            DataColumn iqCountry = new DataColumn();
            iqCountry.ColumnName = "iqCountry";
            iqCountry.Caption = "Страна";
            iqCountry.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqCountry);

            DataColumn iqRegion = new DataColumn();
            iqRegion.ColumnName = "iqRegion";
            iqRegion.Caption = "Регион";
            iqRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqRegion);

            DataColumn iqRegionType = new DataColumn();
            iqRegionType.ColumnName = "iqRegionType";
            iqRegionType.Caption = "Тип региона";
            iqRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqRegionType);

            DataColumn iqSubRegion = new DataColumn();
            iqSubRegion.ColumnName = "iqSubRegion";
            iqSubRegion.Caption = "Район";
            iqSubRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqSubRegion);

            DataColumn iqSubRegionType = new DataColumn();
            iqSubRegionType.ColumnName = "iqSubRegionType";
            iqSubRegionType.Caption = "Тип района";
            iqSubRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqSubRegionType);

            DataColumn iqCity = new DataColumn();
            iqCity.ColumnName = "iqCity";
            iqCity.Caption = "Город";
            iqCity.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqCity);

            DataColumn iqCityType = new DataColumn();
            iqCityType.ColumnName = "iqCityType";
            iqCityType.Caption = "Тип города";
            iqCityType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqCityType);

            DataColumn iqNp = new DataColumn();
            iqNp.ColumnName = "iqNp";
            iqNp.Caption = "НП";
            iqNp.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqNp);

            DataColumn iqNpType = new DataColumn();
            iqNpType.ColumnName = "iqNpType";
            iqNpType.Caption = "Тип НП";
            iqNpType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqNpType);

            DataColumn iqStreet = new DataColumn();
            iqStreet.ColumnName = "iqStreet";
            iqStreet.Caption = "Улица";
            iqStreet.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqStreet);

            DataColumn iqStreetType = new DataColumn();
            iqStreetType.ColumnName = "iqStreetType";
            iqStreetType.Caption = "Тип улицы";
            iqStreetType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqStreetType);

            DataTable SetDT = new DataTable();
            SetDT = SQLiteData.GetSetData(TabName);

            frmClean.cCfg.CheckType = "addrmatch";
            frmClean.cCfg.ErrorRowIndex = -1;
            //frmClean.cCfg.StartInd = Convert.ToInt32(grTables.SelectedRows[0].Cells["Поле чистки"].Value.ToString());
            //,iqStartInd INTEGER,iqnAll INTEGER,iqnGood INTEGER,iqnBad INTEGER,iqnSomn INTEGER,iqStartClean INTEGER
            frmClean.cCfg.StartInd = Convert.ToInt32(SetDT.Rows[0]["iqStartInd"].ToString());
            //frmClean.cCfg.ErrorRowIndex = Convert.ToInt32(SetDT.Rows[0]["iqStartClean"].ToString()) + 1;
            //frmClean.cCfg.nAll = Convert.ToInt32(SetDT.Rows[0]["iqnAll"].ToString());
            //frmClean.cCfg.nGood = Convert.ToInt32(SetDT.Rows[0]["iqnGood"].ToString());
            //frmClean.cCfg.nBad = Convert.ToInt32(SetDT.Rows[0]["iqnBad"].ToString());
            //frmClean.cCfg.nSomn = Convert.ToInt32(SetDT.Rows[0]["iqnSomn"].ToString());
        }


        public class CleanInfo
        {
            public string CleanFileName { get; set; }
            public string FileName { get; set; }
            public Paramm _Paramm { get; set; }
            public CleanInfo()
            {
                CleanFileName = "";
                FileName = "";
                _Paramm = new Paramm();
            }

        }
        public class Paramm
        {
            public string NumberCores { get; set; }
            public string Count { get; set; }

            public Paramm()
            {
                NumberCores = "";
                Count = "";
            }
        }












        
    }//class end

    public partial class templateResponse
    {
        public string GUID { get; set; }
        public string ISOK { get; set; }
        public Addresses[] Address { get; set; }

        public class Addresses
        {
            public string full_name { get; set; }
            public string post_code { get; set; }
            public string KLADR { get; set; }
	        public string region { get; set; }
            public string region_type { get; set; }
            public string subregion { get; set; }
	        public string city { get; set; }
            public string city_type { get; set; }
            public string np { get; set; }
	        public string np_type { get; set; }
            public string street { get; set; }
            public string street_type { get; set; }
	        public string house { get; set; }
            public string Case { get; set; }
            public string build { get; set; }
	        public string liter { get; set; }
            public string vlad { get; set; }
            public string block { get; set; }
	        public string pom { get; set; }
            public string pav { get; set; }
            public string uch { get; set; }
	        public string obsch { get; set; }
            public string kom { get; set; }
            public string flat { get; set; }
	        public string office { get; set; }
            public string kab { get; set; }
            public string abon { get; set; }
            public string vch { get; set; }
            public string comment { get; set; }
            public string ErrorCode { get; set; }
            public string status { get; set; }
            public string lost { get; set; }
           

            public string c_ischeck { get; set; }
            public string c_index_in { get; set; }
            public string c_index_out { get; set; }
            public string c_kladr { get; set; }
            public string c_addr_in { get; set; }
            public string c_addr_out { get; set; }
            public object c_json_kvant { get; set; }
            public string c_struct_kvant { get; set; }
            public string c_house_str { get; set; }
            public string c_status_error { get; set; }
            public string c_house_error { get; set; }
            public string c_house_error_desc { get; set; }

            ////////////////////////////////////////////////////////////////////

            public string c_k5 { get; set; }
            public string k5 { get; set; }
            public string c_index { get; set; }
            public string c_fullname { get; set; }
            public string c_RegionName { get; set; }
            public string c_RegionType { get; set; }
            public string c_SubRegionName { get; set; }
            public string c_SubRegionType { get; set; }
            public string c_CityName { get; set; }
            public string c_CityType { get; set; }
            public string c_NPName { get; set; }
            public string c_NPType { get; set; }
            public string c_StreetName { get; set; }
            public string c_StreetType { get; set; }
            public string c_level { get; set; }
            public string c_typeorder { get; set; }
            public string KEY { get; set; }
            public string RANK { get; set; }
            public string RANK1 { get; set; }
            public string c_kvant { get; set; }
            public string c_status { get; set; }

            //[iqdq4_val].[dbo].[spv_address_search_service_detail]
            public string c_zipcode { get; set; }
            public string c_address_full { get; set; }
            public string c_region_name { get; set; }
            public string c_region_abbr { get; set; }
            public string c_district_name { get; set; }
            public string c_district_abbr { get; set; }
            public string c_city_name { get; set; }
            public string c_city_abbr { get; set; }
            public string c_community_name { get; set; }
            public string c_community_abbr { get; set; }
            public string c_street_name { get; set; }
            public string c_street_abbr { get; set; }
            public string c_addr_lost { get; set; }
            public string msg { get; set; }
            

            public Addresses()
            {

                full_name ="";
                post_code = "";
                KLADR = "";
	            region = "";
                region_type = "";
                subregion = "";
	            city = "";
                city_type = "";
                np = "";
	            np_type = "";
                street = "";
                street_type = "";
	            house = "";
                Case = "";
                build = "";
	            liter = "";
                vlad = "";
                block = "";
	            pom = "";
                pav = "";
                uch = "";
	            obsch = "";
                kom = "";
                flat = "";
	            office = "";
                kab = "";
                abon = "";
                vch = "";
                comment = "";
                ErrorCode = "";
                status = "";
                lost = "";
              

                c_ischeck= "";
                c_index_in= "";
                c_index_out= "";
                c_kladr= "";
                c_addr_in= "";
                c_addr_out= "";
                c_json_kvant= "{}";
                c_struct_kvant= "";
                c_house_str= "";
                c_status_error= "";
                c_house_error= "";
                c_house_error_desc= "";

                ////////////////////////////////////////////////////////////////////

                c_k5= "";
                k5= "";
                c_index= "";
                c_fullname= "";
                c_RegionName= "";
                c_RegionType= "";
                c_SubRegionName= "";
                c_SubRegionType= "";
                c_CityName= "";
                c_CityType= "";
                c_NPName= "";
                c_NPType= "";
                c_StreetName= "";
                c_StreetType= "";
                c_level= "";
                c_typeorder= "";
                KEY= "";
                RANK= "";
                RANK1= "";
                c_kvant= "";
                c_status= "";

       

                c_zipcode = "";
                c_address_full = "";
                c_region_name = "";
                c_region_abbr = "";
                c_district_name = "";
                c_district_abbr = "";
                c_city_name = "";
                c_city_abbr = "";
                c_community_name = "";
                c_community_abbr = "";
                c_street_name = "";
                c_street_abbr = "";
                c_addr_lost = "";
                msg = "";

            }

        };   
    }


   
    public partial class CheckEmailResponse
    {
        /*
        public CheckEmails[] CheckEmail { get; set; }
        public class CheckEmails
        {
            public string status_code { get; set; }
            public string c_message { get; set; }
            public CheckEmails()
            {
                status_code = "";
                c_message = "";
            }
        }*/
        public CheckEmails[] CheckEmail { get; set; }
        public class CheckEmails
        {
            public string c_raw { get; set; }
            public string c_email_out { get; set; }
            public string c_valid { get; set; }
            public string c_status_desc { get; set; }
            public CheckEmails()
            {
                c_raw = "";
                c_email_out = "";
                c_valid = "";
                c_status_desc = "";
            }
        }





    }

    
    public class CheckedEmail
    {
        public string status_code { get; set; }
        public string c_message { get; set; }
        public Statistic_Elements CheckedEmailStatistic { get; set; }

    }

    public class CheckedPhone
    {
        public string kladr_out { get; set; }
        public string phone_formatted { get; set; }
        public string phone_ded { get; set; }
        public string valid { get; set; }
        public string status_desc { get; set; }
        public Statistic_Elements CheckedPhoneStatistic { get; set; }
    }

    public class CheckedFIO
    {
        public string c_lname { get; set; }
        public string c_fname { get; set; }
        public string c_mname { get; set; }
        public string c_gender { get; set; }
        public string c_error { get; set; }
        public string c_error_status { get; set; }
        public Statistic_Elements CheckedFIOStatistic { get; set; }

    }

    public partial class CheckOrgDubl
    {
        public Org[] Orgs { get; set; }
        public class Org
        {
            public string c_user_orgid { get; set; }
            public string c_user_org_cardid { get; set; }
            public string c_itog { get; set; }
            public string c_fullname { get; set; }
            public string c_phone { get; set; }
            public string c_address { get; set; }
            public string c_post_code { get; set; }
            public string c_kladr { get; set; }
            public Statistic_Elements CheckedFIOStatistic { get; set; }
            public Org()
            {
                c_user_orgid = "";
                c_user_org_cardid = "";
                c_itog = "";
                c_fullname = "";
                c_phone = "";
                c_address = "";
                c_post_code = "";
                c_kladr = "";
            }
        }


    }
    
   


    public class Statistic_Elements
    {
        public int nAll { get; set; }
        public int nBad { get; set; }
        public int nGood { get; set; }
        public int nSomn { get; set; }
        public int NumRow { get; set; }
        public string Old_Status { get; set; }
        public string New_Status { get; set; }

        public string CleanType { get; set; }
        public string RowCheckType { get; set; }
       

        public Statistic_Elements()
        {
            nAll = 0;
            nBad = 0;
            nGood = 0;
            nSomn = 0;
            NumRow = -1;
            Old_Status = null;
            New_Status = null;

            CleanType = "addrmatch";
            RowCheckType = "add";
            
        }




        /*
        private string[] FieldsToKvantStruct(System.Windows.Forms.Control.ControlCollection fields)
        {
            string[] res = new string[2];
            res[0] = "";
            res[1] = "";

            foreach (Control cnt in fields)
            {
                if (cnt.GetType() != typeof(System.Windows.Forms.TextBox)) continue;
                if (((TextBox)cnt).Text != "")
                {
                    if (cnt.Name.Substring(2).ToLower() == "c_house"
                         || cnt.Name.Substring(2).ToLower() == "c_case"

                    || cnt.Name.Substring(2).ToLower() == "c_build"

                    || cnt.Name.Substring(2).ToLower() == "c_liter"

                    || cnt.Name.Substring(2).ToLower() == "c_land"

                    || cnt.Name.Substring(2).ToLower() == "c_block"

                    || cnt.Name.Substring(2).ToLower() == "c_unit"

                    || cnt.Name.Substring(2).ToLower() == "c_pav"

                    || cnt.Name.Substring(2).ToLower() == "c_struct"

                    || cnt.Name.Substring(2).ToLower() == "c_pom"

                    || cnt.Name.Substring(2).ToLower() == "c_plot"

                    || cnt.Name.Substring(2).ToLower() == "c_lend"

                    || cnt.Name.Substring(2).ToLower() == "c_hostel")
                        res[0] += cnt.Name.Substring(2).ToLower() + ':' + ((TextBox)cnt).Text + ";";
                    else if (cnt.Name.Substring(2).ToLower() == "c_room"

                     || cnt.Name.Substring(2).ToLower() == "c_entr"

                     || cnt.Name.Substring(2).ToLower() == "c_floor"

                     || cnt.Name.Substring(2).ToLower() == "c_flat"

                     || cnt.Name.Substring(2).ToLower() == "c_office"

                     || cnt.Name.Substring(2).ToLower() == "c_cab"

                     || cnt.Name.Substring(2).ToLower() == "c_abon"

                     || cnt.Name.Substring(2).ToLower() == "c_munit")
                        res[1] += cnt.Name.Substring(2).ToLower() + ':' + ((TextBox)cnt).Text + ";";

                };
            };

            return res;
        }

        
        void KvantToFiels(string data)
        {

            foreach (Control cnt in pnHome.Controls)
            {
                if (cnt.GetType() == typeof(System.Windows.Forms.TextBox)) ((TextBox)cnt).Text = "";
            }

            string[] kvant = data.Split(';');

            for (var i = 0; i < kvant.Length; i++)
            {

                string[] kvp = kvant[i].Split(':');
                foreach (Control cnt in pnHome.Controls)
                {

                    if (cnt.GetType() == typeof(System.Windows.Forms.TextBox) && cnt.Name.Substring(2).ToLower() == kvp[0].ToLower())
                    {
                        ((TextBox)cnt).Text = kvp[1];
                        break;
                    }
                }
            }
        }
          
                //CheckEmail - вызов через wsdl сервисы
        /*
        wsdl_services.Services client = new wsdl_services.Services();
        wsdl_services.result[][] returnclient = { };
        returnclient = client.IQMDM("CheckEmail", EmailOut);
                
        string str = "";
        int i;
        for (i = 0; i < returnclient.Length; i++)
        {
            for (int j = 0; j < returnclient[i].Length; j++)
            {
                str += returnclient[i][j].name + ": " + returnclient[i][j].val + ", \n";
            }
            str += "======================================================================== \n";
        }                
 
       */
    }
}//namespace
